Model.all的备选方案-Model.where(条件)

Model.all的备选方案-Model.where(条件),model,where-clause,has-many-through,ruby-on-rails-6,Model,Where Clause,Has Many Through,Ruby On Rails 6,我的问题非常简单:如何优化以下查询以在数据库增长时不出现性能问题: def projects_not_participating @project = Project.all - Project.joins(:participants).where(participant: {id: current_user.id}) end 我的模型设置如下: def Project has_many :assignments has_many :participants, through: :

我的问题非常简单:如何优化以下查询以在数据库增长时不出现性能问题:

def projects_not_participating
  @project = Project.all - Project.joins(:participants).where(participant: {id: current_user.id})
end
我的模型设置如下:

def Project
  has_many :assignments
  has_many :participants, through: :assignments
end
我试着用

Project.joins(:participant).where.not(participant: {id: current_user.id})

但所有项目都得到了回报。我发现查询返回的是
assignments
中的所有表项,其中
participant\u id
不是
当前用户.id
,并且在此之前没有对项目项进行分组。

实际上,您非常接近解决方案。目前的问题是重复项目。为了避免这种情况,您可以使用
distinct

Project.joins(:participants).where.not(participants: {id: current_user.id}).distinct

我终于找到了解决办法。我在我的
项目
类中添加了一个方法:

def self.not_participating(user)
  where.not(id: user.projects)
end
并在我的
用户
控制器中使用:

def find_projects
  @projects = Project.not_participating(current_user)
end

谢谢,但这不会改变结果。我想我需要一个独特的
参与者
,但我不知道如何做到这一点,我已经为参与者使用了复数符号。它没有抛出错误,结果集只是错误的。这是rails使用您的代码生成的查询
选择不同的“项目”。*从“项目”中选择“工作分配”中的“项目”内部加入“工作分配”。“项目id”=“项目”。“参与者”中的“id”内部加入“参与者”。“id”!=?限制?[[“id”,2],“LIMIT”,11]
查询的问题是
参与者id
实际上不等于
当前用户id
,但是同一个项目有另一个记录,但是另一个参与者,因此项目被包括在结果集中。
def find_projects
  @projects = Project.not_participating(current_user)
end