Calling a method each time an ActiveRecord Object is accessd

Hi,

I know that it is possible to execute code each time data is saved into
a model by using the +validate+ method.

However, is there also a way to execute code each time the data is
accessed, not just when it is changed?

Bye,
Winsmith

Daniel J. wrote:

I know that it is possible to execute code each time data is saved into
a model by using the +validate+ method.

However, is there also a way to execute code each time the data is
accessed, not just when it is changed?

You can create your own accessor methods for a model’s attributes and
put any code you want in there. The attributes hash holds the model’s
attributes so you can get to it from the accessor.

def phone
self.format_phone_number(attributes[:phone])
end


Josh S.
http://blog.hasmanythrough.com

On 7/7/06, Josh S. [email protected] wrote:

def phone
self.format_phone_number(attributes[:phone])
end

There are also the ActiveRecord::Callbacks that might do what you
need; specifically the after_find and after_initialize might work
nicely. They have some weird caveats so check out the docs before
trying them.

http://api.rubyonrails.com/classes/ActiveRecord/Callbacks.html

Cheers,
Chuck V.

I got it! Thanks a lot you two!

Josh, btw, thanks a lot for the excellent has_many :through explanation
in your blog!

bye,
Daniel

Quick correction for later viewers: It appears that the attributes hash
isn’t created with :symbols as implied above. So above example would be

def phone
self.format_phone_number(attributes[“phone”])
end