如果我想让多个模型可以使用以下范围,我该怎么做而不必将它们直接添加到每个模型中?
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) }
答案 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