I持って複数のモデルを1つのレール形式で扱うにはどうすればよいですか?
class Survey < ActiveRecord::Base
has_many :survey_sections
accepts_nested_attributes_for :survey_sections
end
class SurveySection < ActiveRecord::Base
belongs_to :survey
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
belongs_to :survey_section
has_many :answers
belongs_to :question_group
accepts_nested_attributes_for :question_group
accepts_nested_attributes_for :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
end
class QuestionGroup < ActiveRecord::Base
has_many :questions
end
マイコントローラー次のモデル:それは可能であるどのように
def new
@survey = Survey.new
survey_section = @survey.survey_sections.build
survey_section.questions.build
end
def create
@survey = Survey.new(survey_params)
if @survey.save
redirect_to @survey, notice: 'Super'
else
render 'new'
end
end
def survey_params
params.require(:survey).permit(:title, :description, survey_sections_attributes:[:id, :title, questions_attributes:[:id, :text, answers_attributes:[:id, :text]]])
end
はもっとして3つのモデルにデータを保存するには? 現時点では、私は自分のアンケートフォームデータをアンケート、調査セクション、質問モデルに保存することができます。しかし、私はコントローラーの中で、他のモデルにデータを保存することができるかどうかわかりません。
私の提案は、nested_formsの使用を避けることです。これはレール方式と呼ばれていますが、複雑さと結合性が増します。少し手間をかけてフォームを作成し、それに対処するためにFormオブジェクトを使用する方がよいでしょう。あなたはこのアプローチをGoogleにすることができます。 – vladra