0

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
Alexandra
  • 51
  • 3

1 Answers1

0

Using the answer from this question, I had to write the SQL almost manually and use a little bit different approach:

default_scope { where('subjects.id NOT IN (SELECT DISTINCT(
                      backgroundable_job_id) FROM background_jobs)') }
Community
  • 1
  • 1
Alexandra
  • 51
  • 3