gpt4 book ai didi

ruby-on-rails - 如何以一种 rails 形式处理多个模型?

转载 作者:数据小太阳 更新时间:2023-10-29 06:48:53 26 4
gpt4 key购买 nike

我有以下型号

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

我的 Controller :

 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 个模型中保存数据?目前,我可以将调查表数据保存到调查、调查部分和问题模型中。但是我不知道我必须在 Controller 中做什么才能将数据保存到其他模型中。

最佳答案

如果您使用 fields_for,您可以根据需要处理任意数量的表单正确的 helper 。

我认为这就是您的不足之处(您的 Controller 似乎还不错)。

我也是wrote an answer about this有一段时间了。

#app/models/survey.rb
class Survey < ActiveRecord::Base
has_many :sections
accepts_nested_attributes_for :sections
end

#app/models/section.rb
class Section < ActiveRecord::Base
belongs_to :survey
has_many :questions
accepts_nested_attributes_for :questions
end

#app/models/question.rb
class Question < ActiveRecord::Base
belongs_to :section
has_many :answers
end

尝试让您的模型名称尽可能简洁。

#app/controllers/surveys_controller.rb
class SurveysController < ApplicationController
def new
@survey = Survey.new
@survey.sections.build.questions.build
end

def create
@survey = Survey.new survey_params
@survey.save
end

private

def survey_params
params.require(:survey).permit(:title, sections_attributes: [:title, questions_attributes:[:title]])
end
end

#app/views/surveys/new.html.erb
<%= form_for @survey do |f| %>
<%= f.text_field :title %>
<%= f.fields_for :sections do |section| %>
<%= section.text_field :title %>
<%= section.fields_for :questions do |question| %>
<%= question.text_field :title %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>

关于ruby-on-rails - 如何以一种 rails 形式处理多个模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com