问题
I would like to find all SongWriter
s with maiden_name
equals to my_maiden_name
?
Note: my_maiden_name
may be nil
I tried:
SongWriter.where("maiden_name = ?", my_maiden_name)
and it works fine except the case where my_maiden_name = nil
.
When my_maiden_name = nil
, the generated query is:
SELECT `song_writers`.* FROM `song_writers` WHERE (maiden_name = NULL)
rather than:
SELECT `song_writers`.* FROM `song_writers` WHERE maiden_name IS NULL
How could I generalize the active record query to include the case my_maiden_name = nil
?
回答1:
Use the Hash syntax. ActiveRecord will do the conversion for you.
SongWriter.where(:maiden_name => my_maiden_name)
When my_maiden_name
is nil
it will use IS NULL
. Otherwise it will use =
.
来源:https://stackoverflow.com/questions/7500311/rails-3-how-to-find-records-with-field-possibly-equals-to-nil