Alternative for Model.all - Model.where(condition)

我们两清 提交于 2020-04-30 07:09:04

问题


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

My model setup is this:

def Project
  has_many :assignments
  has_many :participants, through: :assignments
end
def Participant
  has_many :assignments
  has_many :projects, through: assignments
end

I tried using

Project.joins(:participant).where.not(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.


回答1:


Actually, you're very close to a solution. The current problem is duplicating projects. To avoid this, you can use distinct:

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



回答2:


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

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

and use this in my User controller:

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


来源:https://stackoverflow.com/questions/57948673/alternative-for-model-all-model-wherecondition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!