【发布时间】:2018-12-06 04:02:39
【问题描述】:
假设我们有一个方法
class MyModel < ActiveRecord::Base
def self.stats
# do something and returns a hash
end
end
该方法需要遍历记录并可能调用each。
我想将此方法与scopes、where、all 等一起使用。如下所示:
MyModel.all.stats
#=> one hash
MyModel.where("created_at > ?", 1.day.ago).stats
#=> another hash
MyModel.funny.stats
#=> funny hash
...
这可能吗?我需要将ActiveRecord Relation 作为参数传递还是将作用域作为参数传递?
【问题讨论】:
-
我忘了说我使用的是 Rails 5.2.0 @SergioTulentsev
标签: ruby activerecord ruby-on-rails-5