减去两个ActiveRecord ::关系对象
问题描述:
我想让我的应用程序的用户有机会从他们的微博中删除不需要的微博。默认情况下,微观柱饲料是从遵循用户做出的用户自己的微柱加上微观柱:减去两个ActiveRecord ::关系对象
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)
我找不到对应于-
阵列操作的任何方法。不过,我在#1的问题找到方法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
会加载所有未隔离的Micropost,这对于数据库来说是一项比加载隔离的微博更重的作业。 merge
方法是否有其他解决方案,例如从原始供稿中减去隔离的微博?
答
对于特定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
答
对于导轨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
end
的feed
返回relation
产生ONY一个DB请求,并且可以与附加的滤波被链接,订货 - 无论你需要什么。
我不确定'microposts_not_to_show'的定义是否正确:它应该返回一个Micropost对象而不是隔离对象:其中的参数包含一个隔离对象。 – Asarluhi
我们正在加入表格。在使用select方法明确指定之前,它不会显示Quarantine对象。 – moyinho20
我收到以下警告:'ActiveRecord :: StatementInvalid:PG :: UndefinedColumn:错误:列quarantines.user_id不存在'。 – Asarluhi