Search code examples
mysqlruby-on-railsrubyfind-by-sql

Ruby on Rails .find_by_sql quotes issue


I am having an issue using the date variable in the following MySQL statement. The date variable contains a string which represents a date.

personal = Event.find_by_sql ["SELECT * 
                                 FROM events 
                                WHERE DATE(start) = ?
                                  AND HOUR(start) = ? 
                                  AND user_id = ?;", date, hour, user]

The following is the resulting query which is run on the database.

SELECT * 
  FROM events 
 WHERE DATE(start) = ''2015-02-27'' 
   AND HOUR(start) = 9 
   AND user_id = 123456789;

An extra set of quotes is added around the date string, which causes an error. Is there any way to get rid of the extra pair of quotes?


Solution

  • Have you tried using where?

    personal = Event.where("DATE(start) = ?", date.to_date).
      where("HOUR(start) = ?", hour).
      where(user_id: user)