【问题标题】:How to DRY named_scope extension如何干燥 named_scope 扩展
【发布时间】:2011-06-23 12:12:14
【问题描述】:

给定以下代码:

  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, :conditions => ['bonus = ?', true] do
    def total_points
      self.sum('point_value')
    end
  end

你会如何干掉重复的 total_points 方法?

环境:Rails 2.3.11

【问题讨论】:

  • 它可以是一个独立的named_scope,你可以链接。
  • 您可以创建名为 total_points 的方法,您可以将其链接到其他范围
  • 这两个方法当然都不错,简单!

标签: ruby-on-rails dry named-scope


【解决方案1】:

单独定义所有范围,然后为您在应用程序中需要的特定类型的集合创建类方法可能会更简洁和更可重用。这是一个简单的示例(使用 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

顺便说一句,我不确定您为什么要将订单与总和组合在一起 - 订单不应该对返回的值产生影响(除非您应用限制)。

【讨论】:

    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2013-09-16
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多