Daniel Jilg
2006-Jul-07 10:45 UTC
[Rails] 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 -- Posted via http://www.ruby-forum.com/.
Josh Susser
2006-Jul-07 20:27 UTC
[Rails] Re: Calling a method each time an ActiveRecord Object is acc
Daniel Jilg 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 Susser http://blog.hasmanythrough.com -- Posted via http://www.ruby-forum.com/.
Chuck Vose
2006-Jul-08 19:14 UTC
[Rails] Re: Calling a method each time an ActiveRecord Object is acc
On 7/7/06, Josh Susser <josh@hasmanythrough.com> wrote:> Daniel Jilg 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]) > endThere 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 Vose
Daniel Jilg
2006-Jul-13 12:11 UTC
[Rails] Re: Re: Calling a method each time an ActiveRecord Object is
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 -- Posted via http://www.ruby-forum.com/.
Daniel Jilg
2006-Jul-13 16:16 UTC
[Rails] Re: Re: Calling a method each time an ActiveRecord Object is
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 -- Posted via http://www.ruby-forum.com/.