问题
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