我的嵌套模型形式在第一层次上工作很好.但是我的印象是,你可以使用acceptance_nested_attributes_for深入许多层次.但是当我尝试下面的代码时,“
Image”属性被附加到顶层的“问题”模型,并且在使用未知属性“Image”错误的表单提交时中断.
我可以使用表单数据手工完成所有的插入,但如果Rails可以自动处理,那么明显的原因会更好.
我究竟做错了什么?我试过改变| af |在“图像做的领域”到它自己的唯一名称,但没有任何影响.
楷模:
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
解决方法
我认为你的表单变量稍有混淆.它应该是:
= form_for @question,:rows => 7 %br %br = af.fields_for :image do |img_form| = img_form.label :title,"Image Title:" = img_form.text_field :title %br = img_form.label :file,"Image File:" = img_form.file_field :file %br = img_form.label :caption,"Image Caption:" = img_form.text_area :caption,value = @case_id) = f.submit
注意form_for … do | f |产生f.fields_for … do | af |,这反过来产生af.fields_for … do | img_form |.
关键是第二个字段.应该是af.fields_for:image do | img_form |而不是f.fields_for:image do | img_form |.