views:

307

answers:

1

Hi, 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  A: 

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

BushyMark
I knew that I needed @instruction = Instruction.new didn't know that I needed to do @instruction.steps.build. Looking back at the tutorial, I realized that I should've read the 'extras' section. Thanks for the help!
thaiyoshi
fantastic! it was a shot in the dark, but it was the weird thing that I noticed when I started using accepts_nested_attributes_forcheers!
BushyMark