ActiveRecord Setter Overloading
Posted by Adam Wiggins on November 13, 2007 at 11:20 PM
When overloading an ActiveRecord setter, I've often done this:
1 def name=(new_name) 2 @old_name = name 3 attributes['name'] = new_name 4 end
However, this doesn't always seem to work (changes to attributes don't seem to stick). Recently I've started doing this:
1 def name=(new_name) 2 @old_name = name 3 super 4 end
Which seems cleaner anyway. I can't seem to find anyone talking about the correct convention - anyone know the right answer here?
Comments
There are 3 comments on this post. Post yours →
Try:
The first way will never work since attributes returns a copy of the attributes hash. The second way will only work if you're already called the corresponding reader method which, via method_missing, lazy-defines the writer method that you're supering.
Use either self['name'] = newname or writeattribute 'name', new_name.
Cheers!
Excellent guys, thanks!
Post a comment
Required fields in bold.