【问题标题】:Rails ActiveRecord find children where attribute is NOT a given valueRails ActiveRecord 查找属性不是给定值的子项
【发布时间】:2016-07-12 00:03:42
【问题描述】:

鉴于Parent 有许多带有status_id 属性的Childs,我想找到所有没有status_id:1 的孩子。换句话说,status_id 可以是nil 或不同的值。但我看到了一些有趣的行为:

Parent.find(1).childs.where(status_id:nil)
=> #<ActiveRecord::AssociationRelation [#<Child id: 1, status_id: nil ...>]

Parent.find(1).childs.where.not(status_id:1)
=> #<ActiveRecord::AssociationRelation []>

【问题讨论】:

  • 你可以写成:Parent.find(1).childs.where("status_id != 1")或Parent.find(1).childs.where("status_id != ?", 1)
  • @KhanhPham 这也不起作用....仍然得到=&gt; #&lt;ActiveRecord::AssociationRelation []&gt;

标签: ruby-on-rails ruby activerecord


【解决方案1】:

This post 建议 SQL 将 NULL (即不存在的东西)视为不能等同于存在的东西。

10 things in MySQL that won’t work as expected 有一个示例需要使用“IS”进行空值检查,如下所示。

Parent.find(1).childs.where("status_id != ? or status_id is null", 1)

【讨论】:

    【解决方案2】:

    这行得通:

    Parent.find(1).childs.where("status_id IS NOT 1")
    

    仍然希望解释为什么

    【讨论】:

      【解决方案3】:

      如果行不存在,将通过异常查找

      parent = Parent.where(id: 1).includes(:childs).first
      parent.childs.where("status_id IS NOT 1") if parent.present?
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-25
        • 2012-05-04
        • 2011-03-18
        • 2013-08-30
        • 1970-01-01
        • 1970-01-01
        • 2015-07-26
        • 2016-04-08
        相关资源
        最近更新 更多