Rails 4 - 嵌套模型(2级)不保存

时间:2014-01-13 04:14:26

标签: ruby-on-rails ruby-on-rails-4 nested-attributes

关于嵌套模型的Noob问题。

我正在使用Rails 4并尝试创建嵌套模型,如下所示:

调查有很多问题 每个问题都有很多答案

我正在关注Rails Casts episode #196以相同的形式创建调查,问题和答案。 Surevey和Realted问题得到保存,但答案不会保存到数据库中。(然而,答案字段显示正确。)

我非常感谢您对此的投入。

谢谢, 麦克

surveys_controller.rb

def index
   @surveys = Survey.all
end

def new
  @survey = Survey.new
  3.times do
    question = @survey.questions.build
    1.times { question.answers.build }
  end
end

def create
  @survey = Survey.new(survey_params)

  respond_to do |format|
    if @survey.save
      format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
      format.json { render action: 'show', status: :created, location: @survey }
    else
      format.html { render action: 'new' }
      format.json { render json: @survey.errors, status: :unprocessable_entity }
    end
  end
end

def survey_params
  params.require(:survey).permit(:name,questions_attributes:[:content,answer_attributes:[:content]])
end

new.html.erb

<h1>New survey</h1>
  <%= render 'form' %>
<%= link_to 'Back', surveys_path %>

_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 |msg| %>
          <li><%= msg %></li>
          <% end %>
          </ul>
          </div>
   <%end%>

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

   <!--Display Questions -->
   <%= f.fields_for :questions do |builder| %>
     <%= render 'question_fields', :f => builder%>
   <% end %>

   <div class="actions">
     <%= f.submit %>
   </div>

<% end %>

_questions_fields.html.erb:

<p>
 <%= f.label :content, "Question" %><br />
 <%= f.text_area :content, :rows => 3 %>
</p>

<!--Display Answers -->
<%=f.fields_for :answers do |builder| %>
   <p>
     <%= render 'answer_fields', :f => builder%>
   </p>
<%end%>

_answers_fields.html.erb:

<p>
 <%= f.label :content, "Answer" %>
 <%= f.text_field :content%>
</p>

调查模型:

 class Survey < ActiveRecord::Base
  has_many :questions, :dependent => :destroy
  accepts_nested_attributes_for :questions
 end

问题模型:

  class Question < ActiveRecord::Base
   belongs_to :survey
   has_many :answers, :dependent => :destroy
   accepts_nested_attributes_for :answers
  end

答案型号:

  class Answer < ActiveRecord::Base
  belongs_to :question
  end

1 个答案:

答案 0 :(得分:2)

修改:尝试在answer_attributes方法中将answers_attributes更改为survey_params

Prying会告诉你答案属性没有通过。


快速浏览后我没有看到任何特别错误,所以你只需要调试。您应该将gem 'pry-rails'添加到您的Gemfile中,然后输入

require 'pry'; binding.pry

在您要调试的行上。我在调查控制器中的创建操作中保存之前就把它放好了。然后提交表单并转到您的服务器。它会被暂停,你会有一个控制台。型

@survey.save
@survey.errors

看看会发生什么。同时输入paramssurvey_params,以确保您的表单数据正常运行。

如果你继续在不同的地方撬动,你会发现什么不起作用。我怀疑你的答案没有被正确地纳入survey_params。当事情没有得到拯救时,强大的属性往往是罪魁祸首。