[英]How to make a scope available to multiple models DRY
If I want to make the following scopes available to multiple models how do I do so without having to add them directly into each model? 如果要使以下范围可用于多个模型,该如何做而不必直接将它们添加到每个模型中?
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) }
One of the prescribed ways is by using concerns . 规定的方法之一是使用关注 。
You should be able to create a file like this at app/models/concerns/dateable.rb
: 您应该能够在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
Then include
it into the models that need it. 然后include
其包含在需要它的模型中。
class Employee < ApplicationRecord
include Dateable
end
class Customer < ApplicationRecord
include Dateable
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.