Jerome
Jerome

Reputation: 6201

Rails query conditions for hour of creation

In an attempt to summarise traffic data base on a time span, one cannot search invoking a component of a datetime object as such:

 txat0 = Transaction.where(['shop_id = ? AND created_at.hour = ?', shop, 0]).count

One could go via the SQL route (i.e. postgresql)

select extract(shop_id, hour from created_at) from transactions

and filter from there.

But what is a succinct way of achieving this with ruby or rails (performance is not a concern for this query) ?

Upvotes: 1

Views: 161

Answers (1)

gd_silva
gd_silva

Reputation: 1025

I believe you could do a mix and run the SQL part inside an ActiveRecord query.

What about:

Transaction.where("DATE_PART('hour', created_at) = ?", 0)

PS: I've ignored the shop_id clause in the above example, but you can just add it afterwards.

Upvotes: 2

Related Questions