Question

I have a view which is exporting some columns, one column is called

'created_at' type:"timestamp without timezone" format: "2014-03-20 12:46:36.590253"

In rails I have a method, which is getting data from the view and is trying to filter the data by a date. I tried rapping created_at into date() but is still not working. Any ideas?

return ActiveRecord::Base.connection.select_all(" select * from db_functions where date(created_at) >= #{date_p} AND date(created_at) <= #{date_p}")

PG::UndefinedFunction: ERROR:  operator does not exist: date >= integer
LINE 2: ...select * from db_functions where date(created_at) >= 2014-03...
                                                         ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
Was it helpful?

Solution

The first noticeable problem is that your time is not quoted. This is causing the time to be treated as integer. To fix this, you could simply wrap date_p with quotes or use ActiveReocrd::ConnectionAdapters#quote as:

conn = ActiveRecord::Base.connection
return conn.select_all("select * from db_functions 
                        where date(created_at) >= #{conn.quote(date_p)} 
                        AND date(created_at) <= #{conn.quote(date_p)}")

Another option, instead of converting each created_at to date in where clause, you could modify date_p to be beginning of the day value and remove the "date" conversion altogether. Also, instead of using values directly in the query, it's better to use prepared statements (Linked article is a couple of years old, but explains prepared statements clearly with examples).

Then there is also the task of modifying the date time parameter to beginning of day. Given that date_p is a string and not a time, here is what you can do:

date_p = Time.zone.parse("2014-03-20 12:46:36.590253").beginning_of_day.utc
return ActiveRecord::Base.connection.select_all("select * from db_functions 
                                                 where created_at >= ? 
                                                 AND created_at <= ?", date_p, date_p)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top