Leo
Leo

Reputation: 2103

assign_attributes and ActiveModel::ForbiddenAttributesError

In my app, I have decided to move some part of logic into the extra class called CategoryForm, which is dedicated to ActiveRecord Category class. Unfortunatelly as i pass params into Category, ActiveModel::ForbiddenAttributesError is raised. Here is Category class:

class Category < ActiveRecord::Base

  has_many :subcategories

  accepts_nested_attributes_for :subcategories

end

CategoryForm class:

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  

and the CategoryController fragment:

def create
    @category = Category.new
    @category_form = CategoryForm.new(@category, params[:category])

Error points into @model.assign_attributes(params) line, and as far as i understand it, my Category is unable to take params with subcategories. But on the other hand thats what nested_attributes are for... Any idea how to enable it correctly or what else is wrong?

Upvotes: 2

Views: 1831

Answers (2)

epsilones
epsilones

Reputation: 11609

Just to complete the answer, you can use in rails 4 the protected_attributes gem which let you work with attr_accessible as in rails3. And here's is a great railscast about the subject. `

Upvotes: 0

jvperrin
jvperrin

Reputation: 3368

The error you are encountering is from Strong Parameters, which was added in Rails 4. Try this code in your controller instead to filter the parameters through Strong Parameters:

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

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

Upvotes: 3

Related Questions