英文:
Rails 7, trying to exclude applicants from a list of projects using joins
问题
我有一个**Project(项目)**模型...
class Project < ApplicationRecord
belongs_to :user
has_many :applicants, dependent: :destroy
end
...还有一个**User(用户)**模型...
class User < ApplicationRecord
has_many :projects, dependent: :destroy
has_many :applicants, dependent: :destroy
end
...以及一个**Applicant(申请者)**模型,用于在多对多关系中连接它们。
class Applicant < ApplicationRecord
belongs_to :project
belongs_to :user
end
我将在Applicant上执行其他操作,因此更倾向于保持这个结构。我还在使用Devise来管理Users(用户)。
我的问题是这样的。我试图返回一个**Projects(项目)**列表,其中满足两个条件。
- 项目列表要排除当前用户自己的项目。这可以通过以下查询实现:
@suggested_projects = Project.where.not(user_id: current_user.id)
- 然后,我想要从这个列表中排除任何用户没有成为申请者的项目。我可以找到用户已经申请的项目如下:
Project.where.not(user_id: current_user.id).joins(:applicants).where(applicants: { user_id: current_user.id })
但是,我似乎无法找到用户没有申请的项目。例如,我尝试了以下查询,但它不起作用:
Project.where.not(user_id: current_user.id).joins(:applicants).where.not(applicants: { user_id: current_user.id })
有人可以指导我正确的方向吗?
英文:
I have a Project model ...
class Project < ApplicationRecord
belongs_to :user
has_many :applicants, dependent: :destroy
end
... a User model ...
class User < ApplicationRecord
has_many :projects, dependent: :destroy
has_many :applicants, dependent: :destroy
end
... and an Applicant model to connect them in a many-to-many.
class Applicant < ApplicationRecord
belongs_to :project
belongs_to :user
end
I will be doing other things with Applicant, so prefer to keep this structure. I am also using Devise for Users.
My issue is this. I am trying to return a list of Projects where two conditions happen.
- The list of Projects exclude the current users own projects. This was achieved with query:
> @sugested_projects = Project.where.not(user_id: current_user.id)
- Then I want to exclude any Projects from this list, where the User has not become an Applicant. I can find where the User has applied with the following:
> Project.where.not(user_id: current_user.id).joins(:applicants).where(applicants: { user_id: current_user.id })
But I can't seem to be able to find where the User has not applied. I tried this for example, but it doesn't work:
> Project.where.not(user_id: current_user.id).joins(:applicants).where.not(applicants: { user_id: current_user.id })
Can anybody point me in the right direction?
答案1
得分: 2
我会使用一个子查询来排除所有current_user
已经成为申请人的项目的id
:
Project
.where.not(user: current_user)
.where.not(id: current_user.applicants.select(:project_id))
英文:
I would do this with a subquery that rejects all projects with an id
that the current_user
has an applicant
for:
Project
.where.not(user: current_user)
.where.not(id: current_user.applicants.select(:project_id))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论