私はRyan Bates RailsCast #196: Nested model form part 1に従おうとしています。ライアンズのバージョンには2つの明らかな違いがあります:1)私はビルトインの足場を使用していて、彼が使用しているように気品ではありません.2)私はレール4を使っています(Ryansがキャスト、それは4ではありません)。RoRネストされた属性は、編集時に重複を生成します。
だからここで私は
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
のようなモデルに関連付けを追加それから私は、ネストされたビューの一部
を追加しました、新たな調査は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つの質問が作成されているということで結構ですので、最終的にはコントローラ。しかし、調査の1つを編集しようとすると、最初の3つの質問は維持され、さらに3つが作成されます。だからではなく、編集された調査のための3つの質問を有するので、私は今6を持っている私は、コントローラの新しい方法に
Rails.logger.debug("New method executed")
を追加し、私がやっているとき、私の知る限り、それは実行されません編集操作。誰かが私が間違っていることを教えてもらえますか?
ご協力いただきありがとうございます。
あなたは、編集を追加し、コントローラのコードにアクションを更新することができますか? – Almaron
もちろん!私は何かが簡潔さの祭壇で失われたと思う。 – conciliator