Ruby on Rails选择日期范围

时间:2015-04-12 16:28:25

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord rails-activerecord

我想让下面的句子起作用,

User.all.select{ |user| user.created_at === DateTime.yesterday..DateTime.today }

User.all.select{ |user| user.created_at == DateTime.yesterday..DateTime.today }

User.all.select{ |user| user.created_at => DateTime.yesterday..DateTime.today }

这不起作用并提示bad value for range错误。

我知道有更有效的方法可以实现这一目标并获得相同的结果,但我对如何使用日期范围进行精选工作感兴趣

2 个答案:

答案 0 :(得分:3)

range = (DateTime.yesterday..DateTime.now)
User.all.select { |user| range.cover?(user.created_at) }

答案 1 :(得分:2)

由于你在Rails 3中,你可以这样做:

User.find(:all, :conditions => {:created_at => DateTime.yesterday.. DateTime.today})

但请注意,此后已将其弃用:

User.where(:created_at => DateTime.yesterday..DateTime.today)