Call a method in model after find in Ruby on Rails

后端 未结 4 1509
情话喂你
情话喂你 2021-01-18 09:08

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.

T

相关标签:
4条回答
  • 2021-01-18 09:47

    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
    
    0 讨论(0)
  • 2021-01-18 09:49

    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.

    0 讨论(0)
  • 2021-01-18 09:59

    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 讨论(0)
  • 2021-01-18 10:01

    Interestingly enough, this will call the method twice... learned that one the hard way.

    class Post < ActiveRecord::Base     
      after_find :after_find
    
      def after_find
        # do something here      
      end 
    end
    
    0 讨论(0)
提交回复
热议问题