我需要查询一天内的评论。该字段是标准时间戳的一部分,是created_at。所选日期来自date_select。

我怎么用ActiveRecord来做呢?

我需要这样的东西:

"SELECT * FROM comments WHERE created_at BETWEEN '2010-02-03 00:00:00' AND '2010-02-03 23:59:59'"

当前回答

请注意,目前接受的答案在Rails 3中已弃用。你应该这样做:

Comment.where(:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day)

或者,如果你想或必须使用纯字符串条件,你可以这样做:

Comment.where('created_at BETWEEN ? AND ?', @selected_date.beginning_of_day, @selected_date.end_of_day)

其他回答

Comment.find(:all, :conditions =>["date(created_at) BETWEEN ? AND ? ", '2011-11-01','2011-11-15'])

如果你只想休息一天,这样做会更容易:

Comment.all(:conditions => ["date(created_at) = ?", some_date])

我用的是3个点,而不是2个。三个点给你一个开始是开放的,结束是封闭的范围,所以如果你对后面的范围进行2次查询,你不能在两个范围中得到相同的行。

2.2.2 :003 > Comment.where(updated_at: 2.days.ago.beginning_of_day..1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" BETWEEN '2015-07-12 00:00:00.000000' AND '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 
2.2.2 :004 > Comment.where(updated_at: 2.days.ago.beginning_of_day...1.day.ago.beginning_of_day)
Comment Load (0.3ms)  SELECT "comments".* FROM "comments" WHERE ("comments"."updated_at" >= '2015-07-12 00:00:00.000000' AND "comments"."updated_at" < '2015-07-13 00:00:00.000000')
=> #<ActiveRecord::Relation []> 

而且,是的,使用瞄准镜总是很好的!

我运行了这段代码,看看选中的答案是否有效,并且不得不尝试交换日期以获得正确的答案。这个工作,

Day.where(:reference_date => 3.months.ago..Time.now).count
#=> 721

如果您认为产出应该是36,那么考虑一下,先生,3天对3个人来说是多少天?

这段代码应该为你工作:

Comment.find(:all, :conditions => {:created_at => @selected_date.beginning_of_day..@selected_date.end_of_day})

要了解更多信息,请查看时间计算

注意:此代码已弃用。如果您使用的是Rails 3.1/3.2,请使用答案中的代码