【发布时间】:2013-06-17 11:21:23
【问题描述】:
我在学习 rails 时想尝试模仿一些 stackoverflow 功能。特别是当问题有很多答案并且评论属于问答系统时,我对问答系统感兴趣。所以,我从关联和嵌套属性开始。嵌套属性的学习来源是 railcast.com,Ryan 正在将表单(问题,答案)添加到 new.html.erb(调查),但我想添加到 show.html.erb。当我这样做时它看起来很好,除非我发布一些东西。首次提交答案后,问题展示呈现已发布的答案、空的答案表单并填充文本答案表单。所以总的来说,我有答案和两种形式(一个是空的,另一个是文本)。如何让答案只呈现空表单?
show.html.erb
@question.answers.each do |answer|
answer.body
end
form_for @question do |f|
f.fields_for :answers do |builder|
builder.text_area :body
end
f.submit
end
问题.rb
has_many :answers
accept_nested_attributes_for :answer
accept_nested_attributes_for :comment
answer.rb
belongs_to :question
accept_nested_attributes_for :comment
comment.rb
belongs_to :answer
belongs_to :question
questions_controller.rb
def show
@question = Question.find(params[:id])
@question.answers.build
end
【问题讨论】:
-
尝试用
f.fields_for :answers, @question.answers.build do |builder|替换fields_for行
标签: ruby-on-rails ruby-on-rails-3 nested-attributes