Rails范围查询模型

时间:2017-05-19 03:10:47

标签: ruby-on-rails activerecord

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

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_...
                                             ^

1 个答案:

答案 0 :(得分:1)

默认情况下,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