对活动记录进行反向合并



我面临Rails(最后是purSQL(问题。

我有三张桌子(模型(。活动/用户/邀请

class Event < ApplicationRecord
has_many :invitations
end
class User < ApplicationRecord
has_many :invitations
has_many :events, through: :invitations
end
class Invitation < ApplicationRecord
belongs_to :event
belongs_to :user
end

我想列出特定用户没有邀请的所有活动。

禁忌(对我来说非常重要(:

  • 我通过Event.开始请求

基本上,我会说它与合并相反,就像merge.not(user.events)

我找到的唯一解决方案是:

Event.where.not(id: user.events.pluck(:id))

但很明显,我不喜欢它。2个查询可能会以某种方式合并为一个查询。

知道吗?

使用select而不是pluck,它将创建子查询,而不是从数据库中提取记录。Rails ActiveRecord子查询

Event.where.not(id: user.events.select(:id))

最新更新