How to add a method to an activerecord collection?

前端 未结 3 1394
时光取名叫无心
时光取名叫无心 2021-02-18 23:37

I would like to add a method to all collections for a specific model. Let\'s say I want to add the method my_complicated_averaging_method to the WeatherData collect

3条回答
  •  悲&欢浪女
    2021-02-19 00:33

    On Rails >= 4 you can to use where(nil) inplace of scoped

    class Foo < ActiveRecord::Base  
      def self.bar
        where(nil).pluck(:id)
      end
    end
    
    Foo.where(id: [1, 2, 3]).order(:id).bar
    

    And further, you can use #scope, for example:

    class Foo < ActiveRecord::Base
      scope :bar, -> {where(nil).pluck(:id)}
    end
    

    Finally, You can write code like Foo.all.bar

提交回复
热议问题