What's the cleanest way to override ActiveRecord's find for both models and collections?

后端 未结 3 1746
旧时难觅i
旧时难觅i 2021-02-06 17:31

I have library code that overrides Ar\'s find method. I also include the module for all Association classes so both MyModel.find and @parent.my_models.find work and apply the co

3条回答
  •  我寻月下人不归
    2021-02-06 18:14

    First of all, make sure you know Ruby's method call inheritance structure well, as without this you can end up stabbing around in the dark.

    The most straightforward way to do this inside an ActiveRecord class is:

    def self.find(*args)
      super
    end
    

    That will apply to associations as well since they use the base finder themselves. Now you just need to do your customization. The complexity of that can vary widely, and I don't know what you're doing so I can't offer any recommendations.

    Also defining this dynamically will be an exercise unto itself, but this should get you pointed in the right direction.

提交回复
热议问题