Trying to find the definitive answer on whether active record associations should be in the list of attr_accessible attributes.
I’ve seen
class Foo
attr_accessible :name
attr_accessible :bars
belongs_to :bar
end
also seen
attr_accessible :bars_id
want to know the proper way to be able to do Foo.new(name: ‘name’ bar: barvar)
As often the definitive answer is: “It depends™”
Only the attributes you want to mass-assign should be made accessible.
So if you want or need to do…
…then you simply have to make
baraccessible.In the end
assign_attributesis called which does a simplesend("#{attribute_name}=", attribute_value)after checking the accessibility of the attribute.Some coding style aspects:
Often mass assignment happens when processing the
paramhash. At least that’s where the security problems are lurking. There you rarely have aBarobject but more often abar_id.However if you work with model instances, most people prefer using the association methods (as @Andrew Nesbitt wrote) because that often has some advantages (automatic saving, automatic update of the association counterpart, cleaner code, …)
So there are reasons to have one or the other or both.
My personal opinion: One should not waste a lot of time on this topic since Rails 4.0 will have a better solution for parameter sanitizing. (See strong_parameters if you want it in Rails 3, too)