Rails where condition with nil value

前端 未结 5 957
我在风中等你
我在风中等你 2021-02-05 03:16

I found out that using where with symbol :my_id => nil and using old school one with ? is different. Could anyone explain me why?

MyTable.where(\"my_id = ? \", n         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 03:57

    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
    

提交回复
热议问题