default_scope不适用于关联模型的范围

时间:2014-10-20 17:28:37

标签: ruby-on-rails-4 default-scope

我的模型设置如下:

class Subject
  has_one :background_job, as: :backgroundable_job
  has_many :sub_subjects

  default_scope { includes(:background_job).where( background_jobs: { backgroundable_job_id: nil } ) } 
end

default_scope返回没有background_job

的主题

这是SubSubject模型:

class SubSubject
  belongs_to :subject

  scope :ordered, -> { joins { subject }.order('subjects.order_number') }
end

但是当我做subject.sub_subjects.ordered时,我收到以下错误:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "background_jobs"
LINE 1: ...ubjects"."id" = "sub_subjects"."subject_id" AND "backgroun...

当我调用subject.subjects(没有订购)时,它可以正常工作

我还尝试使用Subject自己的属性设置default_scope,它也可以正常工作

我无法弄清楚出了什么问题,请帮忙

编辑:

当我执行SubSubject.joins {subject} .order('subjects.order_number')时rails执行的SQL查询是:

SELECT "sub_subjects".* FROM "sub_subjects" INNER JOIN "subjects" ON "subjects"."id" = "sub_subjects"."subject_id" AND (background_jobs.backgroundable_job_id IS NULL) ORDER BY subjects.order_number

1 个答案:

答案 0 :(得分:0)

使用this问题的答案,我必须手动编写SQL并使用一些不同的方法:

default_scope { where('subjects.id NOT IN (SELECT DISTINCT(
                      backgroundable_job_id) FROM background_jobs)') }