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

后端 未结 3 1683
旧时难觅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:13

    'Pedro's answer is right, but there's a small mistake.

    def self.included(base)
      class << base
        base.extend ClassMethods
      end
    end
    

    should be

    def self.included(base)
      base.extend ClassMethods
    end
    

    Using class << base ... end has the effect of calling 'extend' on 'base' in the class-method scope, but there is no method 'base' in ActiveRecord::Base so an error is thrown. Using base.extend by itself will call the 'extend' method of ActiveRecord::Base.

提交回复
热议问题