【问题标题】:Is there a way to combine where and where.not into one condition in Rails?有没有办法在 Rails 中将 where 和 where.not 组合成一个条件?
【发布时间】:2016-08-11 10:40:18
【问题描述】:

我有一个Event 模型,里面有user_id。我想选择此模型的所有对象,指定 user_id 但不包括特定事件。所以我可以用这样的查询来做到这一点:

Event.where(user_id: user.id).where.not(id: id)

但是我可以将这两个where 函数合二为一吗?

我知道,例如,如果我需要查找具有指定 ids 和 user_ids 的事件,我可以这样做:

Event.where(user_id: user_id).where(id: id)

我可以使用一个 where 调用而不是两个来压缩它:

Event.where(user_id: user_id, id: id)

但是如果我使用wherewhere.not,我可以做同样的事情吗?

【问题讨论】:

    标签: sql ruby-on-rails activerecord orm


    【解决方案1】:

    您可以按以下方式编写以添加 where 和 where.not :

    Event.where(
      "user_id = ? AND id != ?",
      user.id,
      id
    )
    

    所以如果 user_id = 1 并且 id = 2 这将返回 user_id 为 1 且没有 id 为 2 的记录 :)

    【讨论】:

      【解决方案2】:

      你可以收集

      Event.where(user_id: 1) + Event.where.not(id: 2)
      

      或拒绝一个参数

      Event.where(user_id: 1).where.not(id: 2)
      

      【讨论】:

        【解决方案3】:

        试试这个,你可以创建两个作用域,然后在链中调用

        scope :with_user, ->(user) {user_id: user.id}
        
        scope :excluded_event, ->(event_ids) { where.not(id: event_ids) }
        
        Event.with_user(user).excluded_event(event_ids)
        

        【讨论】:

        • 真正的 'rubysh' 答案 =)
        猜你喜欢
        • 1970-01-01
        • 2015-01-22
        • 2019-06-09
        • 1970-01-01
        • 2016-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        相关资源
        最近更新 更多