深嵌套 Rails 4 形式 [英] Deep Nested Rails 4 Form

查看:45
本文介绍了深嵌套 Rails 4 形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个模型项,它们接受问题的嵌套属性,而问题接受答案的嵌套属性.我正在尝试创建一个具有相同形式的问题和答案的项目.

I have 3 models Item which accepts nested attributes for questions and questions accept nested attributes for answers. I'm trying to create an item which has a question and an answer in the same form.

item.rb

class Item < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions
end

question.rb

class Question < ActiveRecord::Base
  belongs_to :item

  has_many :answers, dependent: :destroy
  accepts_nested_attributes_for :answers
end

answer.rb

class Answer < ActiveRecord::Base
  belongs_to :question
end

item_controller.rb

class ItemsController < ApplicationController
    def new
      @item = @repository.items.new
      questions = @item.questions.build
      answers = questions.answers.build
    end

    def create
      @item = Item.new(item_params)
      if @item.save
          redirect_to @item, notice: '...'
      else
          render action: 'new'
      end
    end

  private
  def item_params
      params.require(:item).permit(:id, :content, :kind, :questions_attributes => [:content, :helper_text, :kind], :answers_attributes => [:content, :correct])
  end   
end

_form.haml

= simple_form_for(@item) do |f|
    = f.input :kind
    = f.input :content
    = f.simple_fields_for :questions do |q|
        = q.input :content
        = q.simple_fields_for :answers do |a|
            = a.input :content
    = f.submit

表单正确显示并且它正确保存了问题模型.不过,我似乎无法保存答案.

我已经查看了很多在线帮助,但没有一个包含 Rails 4 强参数.

I've already looked at a lot of online help but none are covering it with Rails 4 strong params.

推荐答案

我认为你的问题在于你的强参数:

I think your problem is with your strong params:

def item_params
      params.require(:item).permit(:id, :content, :kind, questions_attributes: [:content, :helper_text, :kind, answers_attributes: [:content, :correct]])
end   

基本上,当您传递深层嵌套表单(其中有多个依赖模型)时,您必须将属性作为其他模型属性的一部分进行传递.你有单独的参数

Basically, when you pass a deep nested form (where you have multiple dependent models), you'll have to pass the attributes as part of the other model's attributes. You had the params as separate

这篇关于深嵌套 Rails 4 形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆