我正在观看railscasts并尝试用自己的双手编写示例。但是我在以下步骤中遇到了麻烦:创建表单。
它需要在调查和问题之间创建关联。但是无法在我的 Rails 应用程序中建立此关联,因此表单中不会出现任何问题
这是代码
调查模型:
class Survey < ActiveRecord::Base
attr_accessible :name, :questions
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
end
问题模型:
class Question < ActiveRecord::Base
attr_accessible :context, :survey_id
belongs_to :survey
end
Surveys_Controller 方法:
# 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
_form.html.erb 中的问题部分
<% f.fields_for :questions do |builder|%>
<%= builder.label :context, "Question" %><br />
<%= builder.text_area :context, :rows => 3 %>
<% end %>
这是我从控制台测试中得到的
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>]