在我的 Rails 应用程序中,项目通过分配分配给用户。现在我想为特定用户检索未分配的项目。SQL查询:
SELECT * FROM projects WHERE id NOT IN (SELECT project_id FROM assignments WHERE user_id = 1
列出用户 1 在 PgAdmin 中输入时所有未分配的项目。
这是我的导轨代码:
class User < ActiveRecord::Base
has_many :assignments, dependent: :destroy
has_many :assigned_projects, through: :assignments, source: :project
has_many :unassigned_projects, :class_name => 'Project', :finder_sql => proc {
["SELECT * FROM projects WHERE id NOT IN (SELECT project_id FROM assignments WHERE user_id = ? )", self.id]
}
这提出了:
ActiveRecord::StatementInvalid - PG::Error: ERROR: column projects.user_id does not exist
LINE 1: SELECT 1 AS one FROM "projects" WHERE "projects"."user_id" = $1
这并不奇怪,因为正确的列是“assignments.user_id”。显然,rails 不尊重第二个 FROM。我的代码有什么问题?
更新: 检查“unassigned_projects”-CollectionProxy 显示,它包含的正是它应该包含的内容。因此,它似乎首先正确组装。但是,之后 PG 在调用时引发错误:
if @unassigned_projects.any?
但如果调用:
if @assigned_projects.any?