AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

ActiveRecord scope based on hour

iteration

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

model scope attempts

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"

Some challenges will have a nil exact.

How can I iterate challenges only where Time.zone.now.strftime('%H') == challenge.exact.strftime('%H')

Upvotes: 0

Views: 214

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You can use date_part(text, timestamp) postgres function:

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

Here is also month, year and so on.

There is an another way with extract(field from timestamp)

where("extract(hour from exact) = ?", Time.zone.now.hour)

Upvotes: 5

Related Questions