Nested models make up Rails 3
I follow along with Railscast 196 in which R Bates makes nested forms. It has a polling model with a has_many association with a Questions model. The poll also accepts the_requested_attribute_name: values. In the new action survey_controller it does the following to create three question fields in the survey form
def new
@survey = Survey.new
3.times { @survey.questions.build }
end
and inside form_for @survey it has the following to create question fields in the form
<% f.fields_for :questions do |builder| %>
<p>
<%= builder.label :content, "Question" %><br />
<%= builder.text_area :content, :rows => 3 %>
</p>
In the video, as soon as he clicks on a new survey, he displays three question fields (along with other form elements). Question related form elements are not showing for me. I think he did this episode before Rails 3 was released, so something changed, however I can't figure out what, except that I can't see the results of the run 3 times (@ survey.questions.build )
Model
class Survey < ActiveRecord::Base
attr_accessible :name
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
The form
<%= form_for @survey do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% f.fields_for :questions do |builder| %>
<p>
<%= builder.label :content, "Question" %><br />
<%= builder.text_area :content, :rows => 3 %>
</p>
<% end %>
<p><%= f.submit %></p>
<% end %>
html form
<form accept-charset="UTF-8" action="/surveys" class="new_survey" id="new_survey" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="AWvA3/JpixF0C3sO8OzA5mMGsJzknvu99eovYv7M78E="></div>
<p>
<label for="survey_name">Name</label><br />
<input id="survey_name" name="survey[name]" size="30" type="text">
</p>
<p><input name="commit" type="submit" value="Create Survey"></p>
</form>
Update
inside the form, I added this
<%= @survey.questions %>
and he shows it
[#<Question id: nil, survey_id: nil, content: nil, created_at: nil, updated_at: nil>, #<Question id: nil, survey_id: nil, content: nil, created_at: nil, updated_at: nil>, #<Question id: nil, survey_id: nil, content: nil, created_at: nil, updated_at: nil>]
so the 3.times in the new Survey controller action obviously work, but for some reason the fields are not showing when I do
<% f.fields_for :questions do |builder| %>
<p>
<%= builder.label :content, "Question" %><br />
<%= builder.text_area :content, :rows => 3 %>
</p>
source to share