If I have two models: Experience and Category which are a many to many association, that looks like this:
class Experience < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :experiences
end
Why sometimes people add a:
attr_accessible :category_ids in the Experience model? I have found myself having to do that so in Rails admin gem I can add categories to a particular experience, but I fail to see why.
If you setup a HABTM relation between Experience and Category, you have, besides other things, available method
Experience#category_ids. This method returns individual ids of categories the current experience has.Now this method has also
Experience#category_ids=variant, so you can use it to assign ids of categories:Now when you have a form that let’s you select categories for an experience, you have only the ids of the selected categories. When you submit the form, those ids get passed to
Experience#category_ids=via mass assigment and if you don’t have thiscategory_idsinattr_accessible, you get an error.