Rails Observer Alternatives for 4.0

前端 未结 12 817
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 05:29

With Observers officially removed from Rails 4.0, I\'m curious what other developers are using in their place. (Other than using the extracted gem.) While Observers were cer

12条回答
  •  我在风中等你
    2020-12-04 05:40

    Take a look at Concerns

    Create a folder in your models directory called concerns. Add a module there:

    module MyConcernModule
      extend ActiveSupport::Concern
    
      included do
        after_save :do_something
      end
    
      def do_something
         ...
      end
    end
    

    Next, include that in the models you wish to run the after_save in:

    class MyModel < ActiveRecord::Base
      include MyConcernModule
    end
    

    Depending on what you're doing, this might get you close without observers.

提交回复
热议问题