【发布时间】:2011-08-21 10:26:11
【问题描述】:
我的嵌套模型表单在第一层深度上运行良好。但我的印象是,您可以使用 Accept_nested_attributes_for 深入许多层次。但是当我尝试下面的代码时,“图像”属性附加到顶级“问题”模型,它在表单提交时中断,出现未知属性“图像”错误。
我可以使用表单数据手动完成所有插入操作,但如果 Rails 可以自动处理它,那么显然会更好。
我做错了什么?我尝试改变 |af|在“:image do”的字段中为其自己的唯一名称,但它没有任何效果。
型号:
class Question < ActiveRecord::Base
has_one :answer
accepts_nested_attributes_for :answer
end
class Answer < ActiveRecord::Base
belongs_to :question
has_one :image
accepts_nested_attributes_for :image
end
class Image < ActiveRecord::Base
belongs_to :answer
end
控制器:
def new
@question = Question.new
answer = @question.build_answer
image = answer.build_image
@case_id = params[:id]
render :layout => 'application', :template => '/questions/form'
end
def create
question_data = params[:question]
@question = Question.new(question_data)
if @question.save
...
end
查看:
= form_for @question, :html => {:multipart => true} do |f|
= f.label :text, "Question Text:"
= f.text_area :text, :rows => 7
%br
%br
=f.fields_for :answer, do |af|
= af.label :body, "Answer Text:"
= af.text_area :body, :rows => 7
%br
%br
= f.fields_for :image do |af|
= af.label :title, "Image Title:"
= af.text_field :title
%br
= af.label :file, "Image File:"
= af.file_field :file
%br
= af.label :caption, "Image Caption:"
= af.text_area :caption, :rows => 7
= hidden_field_tag("case_id", value = @case_id)
= f.submit
【问题讨论】:
标签: forms ruby-on-rails-3