假设我们有一个方法
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
作为参数传递还是将范围作为参数传递?
最佳答案
是的,stats
方法中的范围将是关系
def self.stats
count
end
MyModel.all.stats
# => 10
MyModel.where("created_at > ?", 1.day.ago).stats
# => 5
这是一个很好的资源http://blog.plataformatec.com.br/2013/02/active-record-scopes-vs-class-methods/
如果你想遍历记录,你可以使用 find_each
方法:
def self.stats
find_each do |my_model|
puts my_model.id
end
end
关于ruby - 在 Ruby on Rails 中定义 ActiveRecord 方法以处理不同的 ActiveRecord 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059716/