Rails ActiveRecord之间的日期

Rails ActiveRecord之间的日期

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

ActiveRecord该怎么用呢?

我需要这样的东西:

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


一只名叫tom的猫
浏览 683回答 3
3回答

拉风的咖菲猫

我估计应该有一个默认的活动记录行为。查询日期很难,特别是涉及时区时。无论如何,我使用:&nbsp;&nbsp;scope&nbsp;:between,&nbsp;->(start_date=nil,&nbsp;end_date=nil)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;start_date&nbsp;&&&nbsp;end_date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where("#{self.table_name}.created_at&nbsp;BETWEEN&nbsp;:start&nbsp;AND&nbsp;:end",&nbsp;start:&nbsp;start_date.beginning_of_day,&nbsp;end:&nbsp;end_date.end_of_day) &nbsp;&nbsp;&nbsp;&nbsp;elsif&nbsp;start_date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where("#{self.table_name}.created_at&nbsp;>=&nbsp;?",&nbsp;start_date.beginning_of_day) &nbsp;&nbsp;&nbsp;&nbsp;elsif&nbsp;end_date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where("#{self.table_name}.created_at&nbsp;<=&nbsp;?",&nbsp;end_date.end_of_day) &nbsp;&nbsp;&nbsp;&nbsp;else &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;all&nbsp;&nbsp;&nbsp;&nbsp;end &nbsp;&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby