Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 -- Can't mass assign protected attributes (even though added to attr_accessible)

I have a nested form categories for stores and have it listed as attr_accessible in the store model. But still keep getting the following error:

WARNING: Can't mass-assign protected attributes: category_ids

I've tried all variations of attr_accessible in the store model:

attr_accessible :categories
attr_accessible :category
attr_accessible :category_id
attr_accessible :category_ids

None of them work! Both these models are has_and_belongs_to_many (and have a joining table called categories_stores).

Any advice would be greatly appreciated (I've been banging my head against the wall for two days over this).

UPDATE

I've implemented a temporary fix (which is pretty redundant and not needed if rails just adhered to the above problem). I fixed it by overwriting the create method for ActiveAdmin and looping to insert the association data:

  controller do
    def update
      @store = store.find(params[:id])
      if @store.update_attributes(params[:store])
        @store.categories.delete_all
        params[:store][:category_ids].each do |category_id|
          @store.categories << Category.find(category_id) unless category_id.blank?
        end
        redirect_to :action => :index
      else
        redirect_to :action => :edit, :notice => "Something f'ed up"
      end
    end

  end
like image 584
Hopstream Avatar asked Oct 10 '22 12:10

Hopstream


1 Answers

I believe if you have a joining table called categories_stores, that your assignments will be more along the lines of:

class Store

    has_many :categories, :through => :categories_stores

with a similar setup in the Categories model.

In your form, if you are creating a store, say, and you want to create / add categories for that store, then you may also need to add:

    accepts_nested_attributes_for :categories_stores

to be able to add to that table.

You can read more about nested attributes here: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

like image 151
Steph Rose Avatar answered Oct 13 '22 12:10

Steph Rose