Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to query for a date in a range using Rails 4 and postgres?

I'm trying to select all records with a created_by attribute in a date range:

@start = params[:start].to_datetime
@end = params[:end].to_datetime
@registrations = Registration.where("created_at >= #{ @start } and created_at <= #{ @end }")

But I get an error from postgres that says:

PG::Error: ERROR:  syntax error at or near "T00"
LINE 1: ...M "registrations"  WHERE (created_at >= 2013-06-01T00:00:00+...

I've been searching on this one, but Google isn't coming through this time...

like image 746
croceldon Avatar asked Dec 08 '22 15:12

croceldon


1 Answers

The best way, in my opinion will be to use range in where clause as:

Registration.where(created_at: @start..@end)

This query will not be prone to SQL injections either, since @start and @end are already typecasted in DateTime in your query.

like image 94
kiddorails Avatar answered Dec 11 '22 08:12

kiddorails