2

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?

Mahmut Ali ÖZKURAN
  • 1,120
  • 2
  • 23
  • 28
Will M
  • 23
  • 4
  • 1
    Note, the semi-colon is only required when entering queries in an interactive environment and they should be omitted when using a query interface like that. What value does `date` contain? – tadman Feb 27 '15 at 15:38
  • Does `date` have quotes in the string? `"'2015-02-27'"` – messanjah Feb 27 '15 at 15:44
  • What type is the `start` column? – messanjah Feb 27 '15 at 15:44
  • date does have quotes, because without them it is treated as a mathematical expression and results in 1986 being used in the SQL query. The start column is of type DateTime. – Will M Feb 27 '15 at 15:50

1 Answers1

0

Have you tried using where?

personal = Event.where("DATE(start) = ?", date.to_date).
  where("HOUR(start) = ?", hour).
  where(user_id: user)
messanjah
  • 8,977
  • 4
  • 27
  • 40