Problems with nested form fields showing up

爱⌒轻易说出口 提交于 2019-12-09 14:17:59

问题


I'm attempting to implement nested object forms for my site, using Ryan Daigle's blog post as a guide (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes). For some reason, the nested form fields don't appear in the view.

class Instruction < ActiveRecord::Base
  has_many :steps
  accepts_nested_attributes_for :steps
end

class Step < ActiveRecord::Base
  belongs_to :instruction
end

<% form_for @instruction do |instruction_form| %>
  <%= instruction_form.error_messages %>
  <p>
    <%= instruction_form.label :title %><br />
    <%= instruction_form.text_field :title %>
  </p>
  <p>
    <%= instruction_form.label :difficulty %><br />
    <%= instruction_form.text_field :difficulty %>
  </p>

<% instruction_form.fields_for :steps do |step_form| %>
    <%= step_form.label :explanation, 'Explanation: ' %>
    <%= step_form.text_field :explanation %>

<% end %>

  <p><%= instruction_form.submit "Submit" %></p>
<% end %>

When I change instruction_form.fields_for :steps do |step_form| to instruction_form.fields_for :step do |step_form|, the form renders but upon submission, I get an 'unknown attribute: step' error.

What I'm doing seems to match the tutorial. What should I check? Thanks.


回答1:


What is going on in your controller? I haven't read the tutorial yet, and can't seem to pull it up right now (down?) but are you building out an object in memory to fill out?

in your controller, in your "new" action, make sure that you are

@instruction = Instruction.new
@instruction.steps.build

This will instantiate a Step in memory as a "placeholder" for your form to fill in . . . at least this is what I do in my own controller when using a accepts_nested_attributes_for, and it works great.

Let me know if it works, and once I can pull up the tutorial I may have to edit this



来源:https://stackoverflow.com/questions/818460/problems-with-nested-form-fields-showing-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!