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
Give please. Electricity is
Give please. Electricity is actually made up of extremely tiny particles called electrons, that you cannot see with the naked eye unless you have been drinking. Help me! Can not find sites on the: Alavert. I found only this - Bug bites alavert. Cytomel discount, clenbuterol cytomel, synthroid without prescription or consultation fee. Learn about hypothyroidism a condition where the thyroid gland does not thyroid hormones affect the metabolic processes of the body. Thanks for the help :confused:, Aldon from Solomon.
Post new comment