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

关于嵌套模型的Noob问题。

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

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

我正在关注Rails Casts第196集以相同的forms创建调查,问题和答案。 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

 

New survey

_form.html.erb:

prohibited this survey from being saved:


builder%>

_questions_fields.html.erb:

 


3 %>

builder%>

_answers_fields.html.erb:

 

调查模型:

  class Survey  :destroy accepts_nested_attributes_for :questions end 

问题模型:

  class Question  :destroy accepts_nested_attributes_for :answers end 

答案型号:

  class Answer < ActiveRecord::Base belongs_to :question end 

编辑:尝试在survey_params方法answers_attributes更改为answers_attributes

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


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

 require 'pry'; binding.pry 

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

 @survey.save @survey.errors 

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

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