2015-06-14 2 views
1

Я прочел все остальные вопросы, относящиеся к этой теме, но у меня все еще есть эта проблема. У меня есть вложенная форма внутри вложенной формы. Варианты ответов находятся внутри вопросов, которые находятся внутри опроса. У меня не возникло проблем с настройкой вопросов, и они сэкономили хорошо. Однако варианты ответа не сохраняются, и я не могу понять, где я ошибаюсь.Rails 4 вложенная форма не сохраняется

survey.rb

class Survey < ActiveRecord::Base 
    belongs_to :author 
    has_many :questions, dependent: :destroy 
    has_many :forms, dependent: :destroy 
    has_many :answer_choices, through: :question 

    validates :name, uniqueness: true 

    accepts_nested_attributes_for :questions, reject_if: proc { |attributes| attributes['text'].blank?}, 
    allow_destroy: true 
end 

question.rb

class Question < ActiveRecord::Base 
    belongs_to :survey 
    has_many :responses, dependent: :destroy 
    has_many :answer_choices, dependent: :destroy 
    accepts_nested_attributes_for :answer_choices, reject_if: proc { |attributes| attributes['content'].blank?}, 
    allow_destroy: true 

end 

answer_choice.rb

class AnswerChoice < ActiveRecord::Base 
    belongs_to :question 
end 

survey_controller.rb

def new 
    @survey = Survey.new(author_id: session[:user_id]) 
    @survey.questions.build 
    @survey.questions.each { |question| 4.times { question.answer_choices.build }} 
    end 

    def edit 
    @survey.questions.build 
    @survey.questions.each { |question| 4.times { question.answer_choices.build }} 
    end 

def survey_params 
    params.require(:survey).permit(:name, :description, :author_id, 
     questions_attributes: [:id, :text, :required, :response_type, 
     :_destroy, :number]) 
end 

_form.html.erb

<%= form_for(@survey) do |f| %> 
    <% if @survey.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@survey.errors.count, "error") %> prohibited this survey from being saved:</h2> 

     <ul> 
     <% @survey.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :name %><br> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br> 
    <%= f.text_field :description %> 
    </div> 
    <div class="field"> 
    <%= f.hidden_field :author_id %> 
    </div> 

    <h2>Questions</h2> 
    <%= f.fields_for(:questions) do |ff| %> 
    <%= render 'questions', :f => ff %> 
    <% end %> 
    <div class="actions"> 
    <%= f.submit 'Submit Question'%> 
    </div> 

    <div class="actions"> 
    <%= link_to 'Finish Survey', surveys_path %> 
    </div> 

<% end %> 

_questions.html.erb

<div> 
    <span><%= f.index + 1 %>. </span> 
    <div class="field"> 
    <%= f.hidden_field :number, value: f.index + 1 %> 
    </div> 
    <div class="field"> 
    <%= f.label :text, "Question" %><br> 
    <%= f.text_field :text %> 
    </div> 
    <div class="field"> 
    <%= f.label :response_type %><br> 
    <%= f.select :response_type, [["Yes/No", "yes/no"], ["Short Answer", "string"], ["Long Answer", "text"], ["Multiple Choice", "multi"]] %> 
    </div> 
    <div class="field"> 
    <%= f.label :required %> 
    <%= f.check_box :required %> 
    </div> 
<div> 
    <p>Answer Choices</p> 
    <%= f.fields_for(:answer_choices) do |ff| %> 
    <%= render 'answer_choices', :f => ff %> 
    <% end %> 
</div> 
    <div class="field"> 
    <%= f.label :_destroy %> 
    <%= f.check_box :_destroy %> 
    </div> 
</div> 

_answer_choices.html.erb

<div class="field"> 
    <%= f.label :content %><br> 
    <%= f.text_field :content %> 
</div> 
<div class="field"> 
    <%= f.label :_destroy %> 
    <%= f.check_box :_destroy %> 
</div> 

ответ

0

Несколько изменений в коде.

Измените метод new как это

def new 
    @survey = Survey.new(author_id: session[:user_id]) 
    @questions = @survey.questions.build 
    @answer_choices = 4.times { @questions.answer_choices.build } 
    end 

Ваш survey_params должен выглядеть следующим образом

def survey_params 
    params.require(:survey).permit(:name, :description, :author_id, 
     questions_attributes: [:id, :text, :required, :response_type, 
     :_destroy, :number, answer_choices_attributes: [:id,:content,:_destroy]]) 
end 

И в вашем form коде, измените эти строки

<%= f.fields_for(:questions) do |ff| %> 
<%= f.fields_for(:answer_choices) do |ff| %> 

в

<%= f.fields_for @questions do |ff| %> 
<%= f.fields_for @answer_choices do |ff| %> 
+0

Большое спасибо! Я сделал первые два изменения, но если я внес изменения, которые вы порекомендовали в код формы, он сломался. Тем не менее, он отлично справился с двумя первыми. – RedMeeple

Смежные вопросы