Problems with the appearance of nested form fields

I am trying 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, nested form fields do not 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 is rendered, but after submitting, I get an "unknown attribute: step" error.

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

0


source to share


1 answer


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

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

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

      



This will instantiate Step

in memory as a "placeholder" to populate your form. At least that's what I do in my own controller when using accepts_nested_attributes_for

it and it works great.

Let me know if this works and as soon as I can pick up the tutorial I might have to edit this

+2


source







All Articles