我正在尝试遵循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
然后像这样将关联添加到模型中
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
因此,创建包含三个问题的新调查很好。但是,如果我尝试编辑调查之一,则将保留原来的三个问题,同时还会创建另外三个问题。因此,我现在有6个问题,而不是3个问题。
Rails.logger.debug("New method executed")
据我所知,在执行编辑操作时不会执行该新方法。谁能告诉我我在做什么错?
任何帮助是极大的赞赏!