Rails where condition with nil value

前端 未结 5 886
我在风中等你
我在风中等你 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:58

    For any relational database the predicate (my_id = NULL ) is always false, because NULL never equals anything - not even NULL.

    A more complete explanation is here https://dba.stackexchange.com/questions/166579/why-is-null-ignored-in-query-results/166586#166586.

    ActiveRecord will cope with this very well, even when null is included in an array.

    irb(main):029:0> Book.where(id: 1).to_sql
    => "SELECT ... WHERE \"books\".\"id\" = 1"
    irb(main):030:0> Book.where(id: nil).to_sql
    => "SELECT ... WHERE \"books\".\"id\" IS NULL"
    irb(main):031:0> Book.where(id: [1, nil]).to_sql
    => "SELECT ... WHERE (\"books\".\"id\" = 1 OR \"books\".\"id\" IS NULL)"
    

提交回复
热议问题