有人知道可以轻松确定日期范围的 gem 吗?我很想做 Model.this_year(:created_at).where()... 等。以为我听说过一次。
我在考虑 dues_paid_this_year 或 updated_at_two_hours_ago 的思路。一个 gem 可以像 search_logic 那样通过创建动态范围来做到这一点会让我的世界变得可爱
最佳答案
我不知道有什么 gem ——尽管创造一个 gem 会很酷。话虽这么说,这可能会让你通过:
class Thing < ActiveRecord::Base
# Some date-related scopes
scope :today, where("created_at > ?", Time.now.beginning_of_day)
scope :yesterday, where("created_at < ? and created_at > ?", 1.day.ago.end_of_day, 1.day.ago.beginning_of_day)
scope :this_month, where("created_at > ?", Time.now.beginning_of_month)
scope :last_month, where("created_at < ? and created_at > ?", 1.month.ago.end_of_month, 1.month.ago.beginning_of_month)
scope :this_year, where("created_at > ?", Time.now.beginning_of_year)
###
# All your model stuff goes here
###
# Let's get real tricky with method_missing
# and allow Thing.last_X_days for work for any value of X
private
def self.method_missing(method, *args, &block)
if method.to_s =~ /^last_(\d+)_days$/i
days = method.to_s.match(/^last_(\d+)_days$/i)
return self.where("created_at > ?", days[1].to_i.days.ago.beginning_of_day)
else
super
end
end
end
这将为您提供一些基本范围,例如 Thing.this_month ... 以及一个动态查找器,让您可以执行类似 Thing.last_90_days 的操作并处理任何数字(警告:我有点 method_missing n00b,代码对我有用,但也许有人可以仔细检查它)。
仅供引用,我在这里假设使用 Rails 3。
关于ruby-on-rails - 是否有 ruby/rails gem 可以轻松确定日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7180892/