2013-10-28 54 views
2

在我的應用程序中,我決定將部分邏輯移入名爲CategoryForm的額外類,該類專用於ActiveRecord Category類。不幸的是,當我通過params進入CategoryActiveModel::ForbiddenAttributesError被引發。 這裏是分類等級:assign_attributes和ActiveModel :: ForbiddenAttributesError

class Category < ActiveRecord::Base 

    has_many :subcategories 

    accepts_nested_attributes_for :subcategories 

end 

CategoryForm類:

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是什麼...任何想法如何正確啓用它還有什麼是錯的?

回答

3

您所遇到的錯誤是Strong Parameters,這是Rails中4添加在你的控制器試試這個代碼,而不是通過強大的參數過濾參數:

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

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

感謝您的回答我意識到我應該只使用category_params而不是params [:category],rails 3習慣:p – Leo

+0

@KubaPolaczek不客氣,很高興我能幫忙! – jvperrin

0

只是爲了完成答案,你可以在rails 4中使用protected_attributesgem它允許您使用attr_accessible,如rails3。關於這個主題,這裏有一個很棒的railscast。 `

+0

我的理解是''protected_attributes' gem是爲了向後兼容而提供的,強參數是新應用的首選默認值。 –

相關問題