Model.all的替代方案-Model.where(条件) [英] Alternative for Model.all - Model.where(condition)

查看:88
本文介绍了Model.all的替代方案-Model.where(条件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is quiet simple: How to optimize the following query to not get performance issues once the database is growing:

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

def 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 ,并且未对项目条目进行分组.

but that returned all projects. I found out that the query is returning all table entries in assignments where participant_id is not the current_user.id and not grouping the project entries befor.

推荐答案

我终于找到了解决方案.我在 Project 类中添加了一个方法:

I finally found a solution. I added a method to my Project class:

def self.not_participating(user)
  where.not(id: user.projects)
end

并在我的 User 控制器中使用它:

and use this in my User controller:

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

这篇关于Model.all的替代方案-Model.where(条件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆