ruby-on-rails - 减去两个 ActiveRecord::Relation 对象

标签 ruby-on-rails postgresql activerecord relationship

我想让我的应用程序的用户有机会从他们的微博信息流中删除不需要的微博。默认情况下,微博的 feed 由用户自己的微博加上关注用户的微博组成:

def feed
  following_ids = "SELECT followed_id FROM relationships
                   WHERE  follower_id = :user_id"
  Micropost.where("user_id IN (#{following_ids})
                   OR user_id = :user_id", user_id: id)
end

我创建了一个Quarantine 模型,其中用户和不需要的微博相关联。然后我寻找一个 ActiveRecord::Relation 方法,它允许我从上面的 where 中减去下面的 where:

microposts_ids = "SELECT micropost_id FROM quarantines
                  WHERE  user_id = :user_id"

Micropost.where("micropost_id IN (#{microposts_ids})", user_id: id)

我找不到任何与 - 数组运算符对应的方法。但是我在 Stackoverflow 问题中找到了方法 merge:Combine two ActiveRecord::Relation objects ,据我所知,这将允许我按如下方式链接 wheres:

Micropost.where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id).merge(Micropost.where.not("micropost_id IN (#{microposts_ids})", user_id: id))

不同的是我把第二个where改成了where.not
此解决方案的问题在于,where.not 会加载所有未隔离的微博,与仅加载隔离的微博相比,这对数据库来说是一项更繁重的工作。 merge 方法是否有任何替代解决方案,例如从原始 feed 中减去隔离微博的方法?

最佳答案

对于特定的用户

microsposts_not_to_show = Micropost.joins(:quarantines).where("quarantines.user_id" => user.id)
all_microposts = Micropost.where("user_id" => user.id) + Micropost.joins(:user => : relationships).where("relationships.follower_id" => user.id)
microposts_to_show = all_microposts - microposts_not_to_show

关于ruby-on-rails - 减去两个 ActiveRecord::Relation 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825288/

相关文章:

ruby-on-rails - 在 WHERE 中重构具有两个子选择的查询

ruby-on-rails - 如何在一定大小后删除rails日志文件

python - Django 查询集过滤器文件字段不为空

sql - 获取多个字段的不同信息,其中一些字段为 NULL

SQL Left Join 对每个表进行验证

ruby-on-rails - IN 子句使用事件记录查询库来创建整数列表

ruby-on-rails - Moped::BSON::ObjectId 或 Rails 模型中父 ID 的字符串?

ruby-on-rails - 如何在 Ruby on rails 中上传大文件?

ruby-on-rails - ruby 中的复杂计数

ruby-on-rails - Rails 事件记录 : has_many error (NameError: uninitialized constant)