我想让我的应用程序的用户有机会从他们的微博信息流中删除不需要的微博。默认情况下,微博的 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/