Rails 3: How to find records with field possibly equals to nil?

浪尽此生 提交于 2020-01-03 03:00:32

问题


I would like to find all SongWriters 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!