模型上的 Rails 范围查询



我有一个具有这种关系的模型:

class Plan < ApplicationRecord
  has_many :enrollment_plans
  has_many :enrollments, through: :enrollment_plans
  ...
end

编辑 这是连接表:

class EnrollmentPlan < ApplicationRecord
  belongs_to :enrollment, required: true
  belongs_to :plan, required: true
end

我试图在模型上放置这个范围:

scope :for_enrollment, -> (enrollment) { where('enrollments.enrollment_id = ?', enrollment.id) }

但我收到以下错误。我试图弄清楚为什么我不能做这个查询。我需要将其更改为什么?

pry(main)> Plan.for_enrollment(Enrollment.last).to_a
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "enrollments"
LINE 1: SELECT "plans".* FROM "plans" WHERE (enrollments.enrollment_...
                                             ^
默认情况下,

ActiveRecord 不包含关联,您需要手动添加enrollments查询。尝试:

scope :for_enrollment, -> (enrollment) do
  joins(:enrollments).
  where('enrollments.id = ?', enrollment.id)
end

此范围将使用三个表的联接进行查询:计划、enrollment_plans和注册。您可以对两个表查询执行相同的逻辑:

scope :for_enrollment, -> (enrollment) do
  joins(:enrollment_plans).
  where('enrollment_plans.enrollment_id = ?', enrollment.id)
end

最新更新