我想让我的应用程序的用户有机会从他们的微博上删除不想要的微博。默认情况下,微博的提要是由用户自己的微博加上后续用户的微博组成的:
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)我找不到与-数组操作符相对应的任何方法。但是,我在一个堆栈溢出问题中发现了方法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将加载所有未隔离的microposts,这对数据库来说是一项比仅加载隔离的微站更繁重的工作。对于merge方法,有什么替代的解决方案,例如从原始饲料中减去被隔离的微柱的方法吗?
发布于 2017-06-29 12:51:05
对于特定的user
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发布于 2017-06-29 13:26:32
对于Rails 5,它可能如下所示:
class User < ApplicationRecord
has_many :relationships
# ...
def feed
Micropost
.where(user_id: relationships.select(:followed_id))
.or(Micropost.where(user_id: id))
.where.not(id: Quarantine.select(:micropost_id).where(user_id: id))
end
endfeed返回relation,它生成ony一个DB请求,可以通过额外的筛选、排序来链接--不管您需要什么。
https://stackoverflow.com/questions/44825288
复制相似问题