导轨 3 嵌套模型形式,使用 accepts_nested_attributes_for 2 层深



我的嵌套模型形式在第一级深度上运行良好。 但我的印象是,你可以使用accepts_nested_attributes_for深入很多层次。 但是当我尝试下面的代码时,"图像"属性附加到顶级"问题"模型,并且在表单提交时中断,并显示未知属性"图像"错误。

我可以使用表单数据手动完成所有插入,但如果 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, :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
    = 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, :rows => 7
  = hidden_field_tag("case_id", value = @case_id)
  = f.submit

注意form_for ... do |f|如何生成f.fields_for ... do |af|,而又生成af.fields_for ... do |img_form|

关键是第二fields_for。它应该是af.fields_for :image do |img_form|而不是f.fields_for :image do |img_form|.

相关内容

  • 没有找到相关文章

最新更新