【问题标题】:optimize an active record query omitting nil fields on associated record优化活动记录查询,省略关联记录上的 nil 字段
【发布时间】:2014-03-04 08:02:41
【问题描述】:

我正在尝试从模型中选择除关联记录中具有 nil 字段的记录之外的所有记录。到目前为止,我有这个:

User.where("id NOT IN (?)", User.all(:include => :profile, :conditions => {:profiles => {:first_name => nil, :last_name => nil}}))

我想知道是否有更直接或最佳的方法来做到这一点。

谢谢!

【问题讨论】:

    标签: ruby activerecord orm ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    这样的事情应该可以工作:

    User.includes(:profile).where('profiles.first_name IS NOT ? AND profiles.last_name IS NOT ?', nil, nil)

    更新:将 != 替换为 IS NOT。运算符 != 在 sql 中是不允许的。它现在应该可以工作了。

    【讨论】:

    • 这似乎不起作用。该查询没有返回任何记录,但我发布的那个有一些记录。不知道为什么。看起来应该可以了。
    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多