在Ruby on Rails中查找后调用模型中的方法

我想知道在使用find之后是否可以从模型中调用方法。

after_save ,但是after_find

谢谢,加布里埃尔。

编辑:对于Rails> = 3,请参阅@ nothing-special-here的答案

有。 与after_initializeafter_find是一个特例。 你必须定义方法, after_find :some_method是不够的。 但这应该有效:

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

您可以在API中阅读有关它的更多信息。

如今((26.04.2012)这是正确的方式(和工作!)来做到这一点:

 class SomeClass < ActiveRecord::Base after_find :do_something def do_something # code end end 

有趣的是,这将两次调用该方法……从中学到了一个难的方法。

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

如果您需要在方法中找到找到的对象:

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

更多细节: http : //guides.rubyonrails.org/active_record_callbacks.html#after-initialize-and-after-find