Rails where condition with nil value
The correct SQL syntax is my_id IS NULL
, so if you change your first snippet to the following it will work:
MyTable.where("my_id IS ?", nil).first
Both syntaxes are perfectly fine. It's up to your own preference. However, if it's a parameter and you don't know whether it will be nil
or not, you'd better use:
MyTable.where(:my_id => parameter).first
In rails 4 you can specify the value as null using the new hash syntax.
MyTable.where(my_id: nil).first
For DB for NULL the syntax should be
my_id IS NULL
So you can give it as:
MyTable.where("my_id is NULL ").first