ruby-on-rails – 如何在一个轨道形式中处理多个模型?

我有以下型号
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个以上的模型中保存数据?
目前,我可以将调查表格数据保存到调查,调查部分和问题模型中.但我不知道在控制器中我可以将数据保存到其他模型中.

解决方法

如果正确使用 fields_for帮助程序,则可以根据需要处理任意数量的表单.

这就是你认为(你的控制器似乎没问题).

我还有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 %>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...