rails 5 - #or 和#joins 的范围:如何解决限制?

rails 5 - scope with #or and #joins: how to work around limitations?

User 有很多 Posts

Post 有很多 Comments

User 有很多 Comments

class Post < ApplicationRecord
  ..stuff...

  scope :created_by, ->(user) { where(creator: user) }
  scope :with_comments_by, ->(user) { joins(:comments).where('comments.creator_id = ?'. user.id) }
  ##########========= this is my failure:
  scope :related_to, ->(user) { created_by(user).or(with_comments_by(user) }

(不是我的真实模型,只是坚持 SO 基本应用程序结构)

最后一个范围不起作用,clearly noted:

The two relations must be structurally compatible, they must be scoping the same model, and they must differ only by WHERE or HAVING.

那么,我该如何解决这个问题? (不要说乱七八糟的长句SQL)

我希望能够调用 Posts.related_to(user) 并获取用户 创建的 评论的所有帖子的一个 ActiveRecord 集合 .


我正沿着这条路走下去,但我知道这是反常的:

class Post < ApplicationRecord
  ..stuff...

  scope :created_by, ->(user) { where(creator: user) }
  scope :with_comments_by, ->(user) { joins(:comments).where('comments.creator_id = ?'. user.id) }
  ##########========= this is my failure:
  # scope :related_to, ->(user) { created_by(user).or(with_comments_by(user) }

  def self.related_to(user)
    ary = []
    ary << Post.created_by(user).map(&:id)
    ary << Post.with_comments_by(user).map(&:id)
    Post.find(ary.uniq)
    # so...bad...so yucky
  end

帮助我,SO 社区。我被困在自己的脑海里。

您的 with_comments_by 范围不是您想要的。该范围应该找到 posts,其评论有来自 user 的评论,所以你应该准确地说:

scope :with_comments_by, ->(user) { where(id: Comment.select(:post_id).where(creator_id: user.id)) }

您应该可以在 related_to 中使用您的 or 的那个范围,没有任何投诉。

此版本的 with_comments_by 还将巧妙地处理重复的 post,如果有人对一个 post.[=16= 发表了多次评论,您的 JOIN 可能会产生重复的 post ]