I am watching on railscasts and tried to write the example with my own hands.
But I got an trouble with the step of: Creating The Form.
It requires creating association between Survey and Question.
But this association cannot be established in my rails application so no questions appear in the form
Here are the codes
Survey model:
class Survey < ActiveRecord::Base
attr_accessible :name, :questions
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
Question model:
class Question < ActiveRecord::Base
attr_accessible :context, :survey_id
belongs_to :survey
end
Surveys_Controller method:
# GET /surveys/new
# GET /surveys/new.json
def new
@survey = Survey.new
3.times {@survey.questions.build}
respond_to do |format|
format.html # new.html.erb
format.json { render json: @survey }
end
end
question part in _form.html.erb
<% f.fields_for :questions do |builder|%>
<%= builder.label :context, "Question" %><br />
<%= builder.text_area :context, :rows => 3 %>
<% end %>
Here is what I got from testing in console
irb(main):010:0> @survey = Survey.new
=> #<Survey id: nil, name: nil, created_at: nil, updated_at: nil>
irb(main):011:0> 3.times {@survey.questions.build}
=> 3
irb(main):012:0> @survey.questions
=> [#<Question id: nil, survey_id: nil, context: nil, created_at: nil, updated_a
t: nil>, #<Question id: nil, survey_id: nil, context: nil, created_at: nil, upda
ted_at: nil>, #<Question id: nil, survey_id: nil, context: nil, created_at: nil,
updated_at: nil>]
haha, i am being stupid.
It is a dumb question.
It doesn’t matter about the association.
I made a typing mistake on
<%f.fields_for :questions do |builder|%>it should return some texts inserting into HTML document rather than just processing as ruby code
it should be
<%=f.fields_for :questions do |builder|%>But thank you all of your answers 🙂