I have a model setup like the following:
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
The default_scope returns the subjects that don't have a background_job
Here is the SubSubject model:
class SubSubject
belongs_to :subject
scope :ordered, -> { joins { subject }.order('subjects.order_number') }
end
But when I do subject.sub_subjects.ordered I get the following error:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "background_jobs"
LINE 1: ...ubjects"."id" = "sub_subjects"."subject_id" AND "backgroun...
When I call subject.subjects (without the ordered) it just works fine
I also tried setting a default_scope with a Subject's own attribute, and it works fine as well
I can't figure it out what's wrong, please help
EDIT:
The SQL query that rails performs when I do SubSubject.joins{subject}.order('subjects.order_number') is:
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