Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method in model after find in Ruby on Rails

I would like to know if it is possible to call a method from a model after using find.

Something like after_save, but after_find.

Thank you, Gabriel.

like image 791
Gabriel Bianconi Avatar asked Oct 02 '09 21:10

Gabriel Bianconi


2 Answers

Nowadays ((26.04.2012) this is proper way (and working!) to do that:

class SomeClass < ActiveRecord::Base
  after_find :do_something

  def do_something
    # code
  end
end
like image 169
nothing-special-here Avatar answered Sep 18 '22 13:09

nothing-special-here


Edit: For Rails >= 3, see the answer from @nothing-special-here

There is. Along with after_initialize, after_find is a special case, though. You have to define the method, after_find :some_method isn't enough. This should work, though:

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

You can read more about it in the API.

like image 44
August Lilleaas Avatar answered Sep 21 '22 13:09

August Lilleaas