Overriding Default Getters in ActiveRecord
Submitted by Aaron Longwell on Thu, 2007-04-19 22:18.
I find somewhat frequent occasions where dynamic Model getters are handy. The most common case is where you want to use the value of one attribute unless it's nil, in which case you want to use another attribute instead. You could do @object.field1 || @object.field2, but that's not very DRY if you do it often.
Instead, you can override the default attribute accessor that ActiveRecord builds for you with code like the following:
1 2 val = read_attribute(:field1) 3 return val || self.field2 4 end
The trick is the read_attribute(:symbol) method (it has a sister method: write_attribute(:symbol, value)). That obtains the current ActiveRecord value for the field (which you need to return if it's non empty).

Aaron, I haven't spoken with
Aaron, I haven't spoken with you in some time and I wanted to see what you were involved with. Very interesting topic about overwriting the automatically created field methods that AR creates.
Isn't it amazing how much you can pump into your application at the 'higher level' using AR.
David Kennedy
Wow, cool man, big thanks!
Wow, cool man, big thanks! http://aiodjbwjvgztog.com
Hello my friend, your site
Hello my friend, your site is very good! http://tmesuzsdjcsx.com
Hello my friend, your site
Hello my friend, your site is very good! http://meizcssvuxisxm.com
Post new comment