如何使范围可用于多个型号DRY

时间:2016-07-07 18:22:56

标签: ruby-on-rails scope

如果我想让多个模型可以使用以下范围,我该怎么做而不必将它们直接添加到每个模型中?

    scope :today, -> { where("DATE(created_at) = DATE(?)", Date.today ) }
    scope :yesterday, -> { where("DATE(created_at) = DATE(?)", 1.day.ago) }
    scope :last_week, -> { where("DATE(created_at) = DATE(?)", 1.week.ago) }

1 个答案:

答案 0 :(得分:3)

其中一种规定方法是使用concerns

您应该可以在app/models/concerns/dateable.rb

创建这样的文件
module Dateable
  extend ActiveSupport::Concern

  included do
    scope :today, -> { where("DATE(created_at) = DATE(?)", Date.today ) }
    scope :yesterday, -> { where("DATE(created_at) = DATE(?)", 1.day.ago) }
    scope :last_week, -> { where("DATE(created_at) = DATE(?)", 1.week.ago) }
  end
end

然后include进入需要它的模型。

class Employee < ApplicationRecord
  include Dateable
end

class Customer < ApplicationRecord
  include Dateable
end