ActiveRecord Global Callbacks for all Models

前端 未结 5 873
清酒与你
清酒与你 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:31

    Based on @harish's answer and in this answer (https://stackoverflow.com/a/10712838/2226338):

    class AuditObserver < ActiveRecord::Observer
        Rails.application.eager_load!
        observe ActiveRecord::Base.descendants
    
        def after_save(record)
            ...
        end
    end
    

提交回复
热议问题