2

私のアプリでは、ロジックの一部を ActiveRecordCategoryクラス専用の CategoryForm という特別なクラスに移動することにしました。残念ながら、params を に渡す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ためのものですか...それを正しく有効にする方法、または他に何が間違っているのでしょうか?

4

2 に答える 2