2015-10-01 3 views
6

У меня есть следующие моделиКак обрабатывать несколько моделей в одной форме рельсов?

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-х моделей? На данный момент я могу сэкономить данные моей формы опроса в опросе, разделе обследования и модели вопросов. Но я не знаю, что мне нужно в контроллере, чтобы я мог сохранять данные в других моделях.

+0

Мое предложение состоит в том, чтобы избежать использования nested_forms. Это так называемый рельсовый путь, но он усложняет и много сочетает. Лучше создать форму с небольшим усилием вручную и использовать объект Form для решения этой проблемы. Вы можете использовать этот подход Google. – vladra

ответ

11

Вы можете обрабатывать столько форм, сколько вам нужно, если вы правильно используете вспомогательный помощник fields_for.

Это то место, где вы падаете. Я думаю (ваш контроллер выглядит хорошо).

I также 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 %> 
0

Вы можете получить лучшее объяснение здесь с таким же типом модели

http://railscasts.com/episodes/196-nested-model-form-part-1

#app/models/survey.rb 
class Survey < ActiveRecord::Base 
    has_many :sections, :dependent => :destroy 
    accepts_nested_attributes_for :sections, :allow_destroy => true 
end 

#app/models/section.rb 
class Section < ActiveRecord::Base 
    belongs_to :survey 
    has_many :questions, :dependent => :destroy 
    accepts_nested_attributes_for :questions, :allow_destroy => true 
end 

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

сейчас в контроллере

def new 
    @survey = Survey.new 
    section = @survey.sections.build 
    section.questions.build 
    end 
end 

Теперь во взглядах

<%= form_for @survey do |f| %> 
    <%= f.error_messages %> 
    <p> 
    <%= f.label :name %><br /> 
    <%= f.text_field :name %> 
    </p> 
    <%= f.fields_for :sections do |builder| %> 
    <%= builder.text_field :title %> 
    <%= builder.fields_for :questions do |question| %> 
     <%= question.text_field :content%> 
    <% end %> 
    <% end %> 
    <p><%= f.submit "Submit" %></p> 
<% end %> 
Смежные вопросы