ActiveRecord范围基于小时

时间:2017-06-05 05:09:26

标签: ruby-on-rails ruby postgresql

迭代

<% @challenges.with_exact.each do |challenge| %>
 etc...
<% end %>

模型范围尝试

scope :with_exact, -> { where("exact == ?", Time.zone.now.hour) } # Error: PG::UndefinedFunction: ERROR:  operator does not exist: time without time zone == integer
scope :with_exact, -> { where(exact: Time.zone.now.hour) } # Error: PG::InvalidDatetimeFormat: ERROR:  invalid input syntax for type time: "13"

有些挑战的确有nil个。

如何仅在Time.zone.now.strftime('%H') == challenge.exact.strftime('%H')

的位置迭代挑战

1 个答案:

答案 0 :(得分:4)

您可以使用date_part(text, timestamp) postgres功能:

where("date_part('hour', exact) = ?", Time.zone.now.hour)

此处还有monthyear等等。

extract(field from timestamp)

还有另一种方法
where("extract(hour from exact) = ?", Time.zone.now.hour)