ruby-on-rails – 是否有ruby/铁轨宝石,使得范围日期变得容易
发布时间:2020-12-17 07:08:30 所属栏目:百科 来源:网络整理
导读:有谁知道一个宝石,使范围日期容易?我喜欢做Model.this_year(:created_at).where()……等等.我以为我听过一次. 我正在考虑dues_paid_this_year或updated_at_two_hours_ago的内容.通过创建动态范围可以像search_logic这样做的宝石会让我的世界变得可爱 解决
有谁知道一个宝石,使范围日期容易?我喜欢做Model.this_year(:created_at).where()……等等.我以为我听过一次.
我正在考虑dues_paid_this_year或updated_at_two_hours_ago的内容.通过创建动态范围可以像search_logic这样做的宝石会让我的世界变得可爱 解决方法
我不知道有什么宝石 – 虽然创造它会很酷.话虽如此,这可能会让你:
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,Time.now.beginning_of_month) scope :last_month,1.month.ago.end_of_month,1.month.ago.beginning_of_month) scope :this_year,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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |