有很多方法可以做到这一点,你的方法是完全有效的(尽管我个人更喜欢将类方法包装到单独的块检查中this https://stackoverflow.com/questions/2505067/class-self-idiom-in-ruby出),但随着人们向模型中添加更多业务逻辑并盲目遵循“瘦控制器,胖模型”的概念,模型变得一团糟。
为了避免这种混乱,最好引入服务对象,在您的情况下,它会是这样的:
class AverageWeatherData
class << self
def data(collection)
new(collection).data
end
end
def initialize(collection)
@collection = collection
end
def data
@collection.reduce do |avg, post|
# reduce goes through every post, each next iteration receives in avg a value of the last line of iteration
# do something with avg and post
end
# no need for explicit return, every line of Ruby code returns it's value
# so this method would return result of the reduce
# more on reduce: http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-reduce
end
end
现在您可以通过将您的集合传递给它来直接调用此类。但您也可以像这样代理调用:
def self.my_complicated_averaging_method
AverageWeatherData.data(@relation)
end
我鼓励您通过阅读此博客来了解更多有关此方法的信息:http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
UPD
您是对的,使用实例变量是搞乱对象内部的一种可能方法(而且它不是公共接口,将来可能会改变)。我的建议是使用方法scoped
。基本替换@relation
with scoped
.
检查这个例子。我使用了我自己项目中的模型来证明它确实有效
2.0.0p247 :001 > Tracking # just asking console to load this class before modifying it
# => Tracking(id: integer, action: string, cookie_id: string, ext_object_id: integer, created_at: datetime, updated_at: datetime)
2.0.0p247 :002 > class Tracking
2.0.0p247 :003?> def self.fetch_ids
2.0.0p247 :004?> scoped.map(&:id)
2.0.0p247 :005?> end
2.0.0p247 :006?> end
# => nil
2.0.0p247 :007 >
2.0.0p247 :008 > Tracking.where(id: (1..100)).fetch_ids
# Tracking Load (2.0ms) SELECT "trackings".* FROM "trackings" WHERE ("trackings"."id" BETWEEN 1 AND 100)
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
UPD
在 Rails 4 中scoped
已被弃用,因此使用是正确的all
.
all.map(&:id)