私のアプリでは、ロジックの一部を 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
ためのものですか...それを正しく有効にする方法、または他に何が間違っているのでしょうか?