ForbiddenAttributesError

ForbiddenAttributesError

在我的应用程序中,我决定将逻辑的一部分移到名为categoryform的额外类中,该类专用于activerecordCategory类。不幸的是,当我将参数传递到Category时,ActiveModel::ForbiddenAttributesError被提升。
这里是分类类:

class Category < ActiveRecord::Base

  has_many :subcategories

  accepts_nested_attributes_for :subcategories

end

类别窗体类:
class CategoryForm

  attr_accessor :model

  def initialize(model, params = {})
    @model = model
    @model.assign_attributes(params)
    build_subcategories
  end

  def save
    delete_empty_subcategories
    @model.save
  end

  private

  def build_subcategories
    8.times { @model.subcategories.build}
  end

  def delete_empty_subcategories
    @model.subcategories.each { |subcategory| subcategory.delete if subacategory.empty?}
  end

end

以及categorycontroller片段:
def create
    @category = Category.new
    @category_form = CategoryForm.new(@category, params[:category])

错误指向@model.assign_attributes(params)行,据我所知,我的Category无法获取具有子类别的参数。但另一方面这就是nested_attributes的作用…你知道如何正确地启用它吗?还有什么问题吗?

最佳答案

您遇到的错误来自rails 4中添加的Strong Parameters。请在控制器中尝试此代码,以通过强参数筛选参数:

def create
  @category = Category.new
  @category_form = CategoryForm.new(@category, category_params)
  # ...
end

private
  def category_params
    params.require(:category).permit!
  end

关于ruby-on-rails - Assign_attributes和ActiveModel::ForbiddenAttributesError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19647016/

10-13 00:49