【问题标题】:Does not equal conditional不等于条件
【发布时间】:2011-08-25 14:56:41
【问题描述】:

我想要一个带有相等和不相等条件的 where 子句:

@user = User.where(:user_id => current_user.id, :author_id != current_user.id).nil? ? (render :something) : (render :somethingelse)

上述方法不起作用:

语法错误,意外')', 期待 tASSOC ...d, :user_id != current_user.id).nil? ? (使成为 :index) : (重新...

但是,如果我将第二个条件从 != 更改为 =>,它将起作用。

如何在一个 where 类中同时满足这两个条件?谢谢

【问题讨论】:

  • @taro 我本周完成了“Ruby on Rails 教程:通过示例学习 Rails”,但它没有涵盖那些条件,所以我还在学习。它还建议我先从 Rails 开始,然后再转向 Ruby。但感谢您的反馈。
  • 您应该使用empty? 而不是nil?,因为where 本身返回一个数组。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

不确定您是否知道,不等于条件通常与 (author_id) NULL 值不匹配。如果需要,您必须发送OR author_id IS NULL

@users = User.where("user_id = ? AND (author_id != ? OR author_id IS NULL)", 
                    current_user.id, current_user.id)

render(@users.present? ? :something : :somethingelse)

另外请注意,我使用的是@users.present?,因为where finder 返回一个ActiveRecord::Relation 数组。

【讨论】:

    【解决方案2】:

    Rails 4 解决了这一切

    Model.where.not(:colname => nil)
    #=> returns all records whose :colname values are not nil
    

    【讨论】:

      【解决方案3】:

      以下是使用 Arel 生成查询“select * from users where user_id = ? and author_id != ?”的方法:

      users = User.arel_table
      User.where(users[:user_id].      eq(current_user.id).and(
                 users[:author_id].not_eq(current_user.id)))
      

      使用 Arel 不如对简单条件使用 Hash 条件简洁,但它的功能要强大得多!

      这是 Arel 提供的 full list of predicationseqnot_eqgtlt 等)的链接。

      【讨论】:

      • 这个答案更好,因为它与数据库无关。例如,一些数据库不理解!=,但其他数据库会。
      【解决方案4】:

      http://guides.rubyonrails.org/active_record_querying.html#hash-conditions

      哈希条件只能进行相等、范围和子集检查。

      您需要下拉到直接 SQL 或反转和 arel 查询,请参阅Is there a way to invert an ActiveRecord::Relation query?

      【讨论】:

        【解决方案5】:

        我相信,应该是:

        @user = User.where(['user_id = ? AND author_id <> ?', current_user.id, current_user.id])
        render(@user ? :something : :somethingelse)
        

        【讨论】:

        • 感谢您的帮助。猜猜我不能用 .nil 把它全部放在一条线上?正如我所希望的那样:)
        【解决方案6】:

        语法错误是由于您尝试使用!= 而不是=&gt;where 方法不支持带有散列参数的不等式,因此您的不等式需要使用数组参数来编写。

        User.where(:user_id => current_user.id).where(['users.author_id <> ?', current_user.id])
        

        【讨论】:

        • 谢谢道格拉斯。有没有办法使用 :author_id 而不是将其作为引号内的文字? (没关系,只是好奇)
        • 我可以添加的唯一建议是查看 meta_where,它实际上支持与您在问题中发布的非常相似的语法。 github.com/ernie/meta_where
        • 如果您使用 Arel,您还可以使用 :author_id 代替字符串(请参阅下面的答案)...
        猜你喜欢
        • 2021-07-17
        • 2011-09-03
        • 1970-01-01
        • 2020-02-20
        • 2014-08-13
        • 2016-02-21
        • 1970-01-01
        • 2016-06-18
        • 2021-12-17
        相关资源
        最近更新 更多