Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where date is greater than given date query

Trying to search where movies coming out have a release date greater than today's date

 Movie.where('release > ?', Date.today)
ActiveRecord::StatementInvalid: Mysql::ParseError: You have an error in your SQL     syntax;    check the manual that corresponds to your MySQL server version for the right syntax to use near 'release > '2011-09-25')' at line 1: SELECT `movies`.* FROM `movies` WHERE (release > '2011-09-25')
like image 633
Mike Avatar asked Sep 26 '11 01:09

Mike


3 Answers

Rails 3+ :

Movie.where('release > ?', DateTime.now)

Pre Rails 3

Movie.where(['release > ?', DateTime.now])
like image 57
Adam Eberlin Avatar answered Nov 13 '22 15:11

Adam Eberlin


In recent versions of rails, you can do this:

User.where(created_at: 3.days.ago..Time.now)

See some other examples here: https://stackoverflow.com/a/24150094

like image 37
Patrick Avatar answered Nov 13 '22 16:11

Patrick


Update

Rails core team decided to revert this change for a while, in order to discuss it in more detail. See this comment and this PR for more info.

I am leaving my answer only for educational purposes.


new 'syntax' for comparison in Rails 6.1 (Reverted)

Movie.where('release >': DateTime.now)

Here is a link to PR where you can find more examples.

like image 15
Marian13 Avatar answered Nov 13 '22 15:11

Marian13