Call a method in a model after searching in Ruby on Rails

I would like to know if a method can be called from a model after using find.

Something like after_save , but after_find .

Thanks, Gabriel.

+6
ruby-on-rails model
source share
4 answers

Edit: for Rails> = 3 see answer from @ nothing-special-here

There is. Together with after_initialize , after_find is a special case. You must define a method, after_find :some_method not enough. This should work, however:

 class Post < ActiveRecord::Base def after_find # do something here end end 

You can learn more about this in the API .

+4
source share

Currently ((04/26/2012) this is the correct way (and it works!)):

 class SomeClass < ActiveRecord::Base after_find :do_something def do_something # code end end 
+11
source share

Interestingly, this will call the method twice ... found out that this is the hard way.

 class Post < ActiveRecord::Base after_find :after_find def after_find # do something here end end 
+2
source share

If you need the found object in your method:

 class SomeClass < ActiveRecord::Base after_find{ |o| do_something(o) } def do_something(o) # ... end end 

More details here: http://guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find

0
source share

All Articles