问题描述
|
给出以下代码:
named_scope :by_order,:order => \'priority ASC\' do
def total_points
self.sum(\'point_value\')
end
end
named_scope :required,:conditions => [\'bonus = ?\',false] do
def total_points
self.sum(\'point_value\')
end
end
named_scope :bonus,true] do
def total_points
self.sum(\'point_value\')
end
end
您将如何干燥重复的total_points方法?
环境:Rails 2.3.11
解决方法
分别定义所有范围,然后为您的应用程序中所需的特定类型的集合创建类方法,可能更干净,更可重用。这是一个简单的示例(使用Rails 3语法,但移植起来应该相当容易)。请注意,我已重命名了某些范围以更好地反映它们的实际作用。
class Thing << ActiveRecord::Base
scope :in_priority_order,order(\"priority\")
scope :no_bonus,where(:bonus => false)
scope :with_bonus,where(:bonus => true)
scope :total_points,sum(:point_value)
def self.total_bonus_points
with_bonus.total_points
end
def self.total_no_bonus_points
no_bonus.total_points
end
end
顺便说一句,我不确定为什么要将订单与总和相结合-订单不应影响返回的值(除非您应用限制)。