【问题标题】:get the complement of a scope in rails / a scope that filters out matching entries在rails中获取范围的补充/过滤掉匹配条目的范围
【发布时间】:2010-11-02 16:55:09
【问题描述】:

我正在构建一个模型来跟踪给定用户已阅读的帖子(在 Rails 3 中)。跟踪这个的表是“读数”。阅读属于:用户和:帖子,两者都有很多:阅读。当用户看到一篇文章时,它被标记为已读,并使用 user_id 和 post_id 创建一个“正在阅读”。这似乎工作正常,但现在我正在尝试编写一个只返回给定用户的未读帖子的范围。查找已读帖子工作正常:

scope :read, lambda { |user_id = nil |       
    user_id.nil? ? {} : joins(:readings).where('readings.user_id = :user_id', :user_id => user_id)
}

但是,我尝试返回该集合的补充(未读帖子)失败了。如何才能做到这一点?有没有一种通用的方法来编写一个只返回另一个(这里,:read)的补码的范围(方法)?我也很乐意将其编写为与作用域相同的类方法。

请记住,只有在阅读帖子时才会创建读数,因此新帖子不会有读数。这似乎比为每个用户为每个新帖子创建条目更经济。

编辑:好的,我越来越近了 - 下面的范围几乎可以工作,但不需要帖子的所有读数都不等于 user_id。因此,如果用户#1 已阅读帖子,用户#2 也已阅读,则查询其他阅读并发现不相等。所以该帖子被错误地发现为未读。

scope :unread, lambda { |user_id = nil |       
    user_id.nil? ? {} : includes(:readings).where('(readings.user_id IS NULL OR readings.user_id != :user_id)', :user_id => user_id)
}

【问题讨论】:

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


    【解决方案1】:

    嗯,它看起来像下面的作品。不过还在测试。如果有人在这里找到一个洞,很乐意重新打开。

    scope :unread_by, lambda { |user_id = nil, hide_unread = nil|
          { :joins => "LEFT JOIN readings ON  readings.post_id    = post.id
              AND readings.user_id        = #{user_id}",
              :conditions => 'readings.id IS NULL' }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多