深嵌套导轨4表格

 mobiledu2502854717 发布于 2023-02-05 11:27

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

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强大的参数覆盖它.

1 个回答
  • 我认为你的问题在于你强大的障碍:

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

    基本上,当您传递深层嵌套表单(您有多个依赖模型)时,您必须将属性作为其他模型属性的一部分传递.你把params分开了

    2023-02-05 11:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有