ActiveRecord Global Callbacks for all Models

前端 未结 5 859
清酒与你
清酒与你 2020-12-31 20:06

I have around 40 models in my RoR application. I want to setup a after_save callback for all models. One way is to add it to all models. Since this callback has the same cod

5条回答
  •  春和景丽
    2020-12-31 20:53

    You should use observers for this:

    class AuditObserver < ActiveRecord::Observer      
    
      observe ActiveRecord::Base.send(:subclasses)
    
      def after_save(record)
        AuditTrail.new(record, "UPDATED")
      end
    end
    

    In order to activate an observer, list it in the config.active_record.observers configuration setting in your config/application.rb file.

    config.active_record.observers = :audit_observer
    

    Note

    In Rails 4, the observer feature is removed from core. Use the https://github.com/rails/rails-observers gem.

提交回复
热议问题