微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何干燥named_scope扩展名

如何解决如何干燥named_scope扩展名

| 给出以下代码
  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
顺便说一句,我不确定为什么要将订单与总和相结合-订单不应影响返回的值(除非您应用限制)。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。