我正在尝试关注Ryan Bates RailsCast#196:嵌套模型表单第1部分.Ryans版本有两个明显的区别:1)我正在使用内置脚手架而不是他正在使用的漂亮,2)我正在运行rails 4(我真的不知道Ryans在他的演员阵容中使用的是什么版本,但它不是4).
所以这就是我做的
rails new survey2
cd survey2
bundle install
rails generate scaffold survey name:string
rake db:migrate
rails generate model question survey_id:integer content:text
rake db:migrate
Run Code Online (Sandbox Code Playgroud)
然后我将关联添加到模型中
class Question < ActiveRecord::Base
belongs_to :survey
end
Run Code Online (Sandbox Code Playgroud)
所以
class Survey < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions
end
Run Code Online (Sandbox Code Playgroud)
然后我添加了嵌套视图部分
<%= form_for(@survey) do |f| %>
<!-- Standard rails 4 view stuff -->
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.fields_for :questions do |builder| %>
<div>
<%= …Run Code Online (Sandbox Code Playgroud)