我正试图跟随Ryan Bates的RailsCast#196:嵌套模型表单第1部分。与Ryan的版本有两个明显的区别:1)我使用内置的脚手架而不是他使用的nifty,2)我正在运行rails 4(我不知道Ryan在他的录制中使用的是哪个版本,但它不是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
然后我像这样将关联关系添加到模型中
class Question < ActiveRecord::Base
belongs_to :survey
end
因此
class Survey < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions
end
然后我添加了嵌套视图部分
<%= 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>
<%= builder.label :content, "Question" %><br/>
<%= builder.text_area :content, :rows => 3 %>
</div>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
最后,需要将控制器设置成这样,以便每当实例化一个新的调查时,就会创建3个问题。
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
# Standard rails 4 index and show
# GET /surveys/new
def new
@survey = Survey.new
3.times { @survey.questions.build }
Rails.logger.debug("New method executed")
end
# GET /surveys/1/edit
def edit
end
# Standard rails 4 create
# PATCH/PUT /surveys/1
# PATCH/PUT /surveys/1.json
def update
respond_to do |format|
if @survey.update(survey_params)
format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
# Standard rails 4 destroy
private
# Use callbacks to share common setup or constraints between actions.
def set_survey
@survey = Survey.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
params.require(:survey).permit(:name, questions_attributes: [:content])
end
end
因此,创建一个具有三个问题的新调查是可以的。但是,如果我尝试编辑其中一个调查,原始的三个问题将被保留,同时另外创建了三个问题。因此,经过编辑的调查不再是3个问题,而是6个问题。我添加了
Rails.logger.debug("New method executed")
在控制器中使用了新的方法,但据我所知,在执行编辑操作时它并没有被执行。请问我做错了什么?
非常感谢任何帮助!