This is probably very stupid question but here we go
class Foo < ActiveRecord::Base
attr_accessor :group_id
end
From irb
# gets record which has group_id set to 106
foo = Foo.find(1)
foo.group_id
=> nil
If I go and remove
attr_accessor :group_id
All works as it should
foo = Foo.find(1)
foo.group_id
=> 106
My question is why? Shouldn’t attr_accessor create accessor / mutator for property :group_id and that why all should be working. What am I missing?
Update
Good answers bellow, just as explanation for my motivation here is I want to use mass assignment of certain properties (you need this since Rails 3.2.x). For that you need attr_accessible , I find that code is much cleaner that way, of course if used responsibly 🙂
Looks like
group_idis already a property on yourFooobject (shown by the fact that it returns 106 whenattr_accessoris omitted). By addingattr_accessoryou are overriding what’s already there and creating a method reader and writer calledgroup_id. The return of the newly definedgroup_idis nil since you don’t define anything.Conceptually, you’re ending up with something like this:
Edit:
If your goal is expose properties then yes, use
attr_accessible