我的问题很简单:如何优化以下查询以避免数据库增长时出现性能问题:
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
enddef Participant
has_many :assignments
has_many :projects, through: assignments
end我试着用
Project.joins(:participant).where.not(participant: {id: current_user.id})但这还了所有的项目。我发现查询正在返回assignments中的所有表条目,其中participant_id不是current_user.id,并且没有对项目条目进行分组。
发布于 2019-09-18 22:37:23
我终于找到了解决办法。我向我的Project类添加了一个方法:
def self.not_participating(user)
where.not(id: user.projects)
end并在我的User控制器中使用:
def find_projects
@projects = Project.not_participating(current_user)
end发布于 2019-09-16 08:37:01
实际上,你离解决方案很近。目前的问题是重复项目。为了避免这种情况,可以使用distinct
Project.joins(:participants).where.not(participants: {id: current_user.id}).distincthttps://stackoverflow.com/questions/57948673
复制相似问题