Rails Problem I encountered when used scope inside scope

scope :non_marked, -> {
  where(results_passed: nil)
}

scope :next_up, -> {
  non_marked.where.not(scheduled_date: nil).
      where('scheduled_date > ?', DateTime.now).
      order(scheduled_date: :asc).
      limit(1).first
}

The scope ‘next_up’ should have returned empty collection but iT was returning data as if I was calling `pact.drug_tests`. see query

Pact Load (0.4ms) SELECT "pacts".* FROM "pacts" WHERE "pacts"."deleted_at" IS NULL AND "pacts"."id" = $1 LIMIT 1 [["id", 1]]
DrugTest Load (0.3ms) SELECT "drug_tests".* FROM "drug_tests" WHERE "drug_tests"."pact_id" = $1 AND "drug_tests"."results_passed" IS NULL AND ("drug_tests"."scheduled_date" IS NOT NULL) AND (scheduled_date > '2016-02-03 14:35:18.718970') ORDER BY "drug_tests"."scheduled_date" ASC LIMIT 1 [["pact_id", 1]]
 DrugTest Load (0.3ms) SELECT "drug_tests".* FROM "drug_tests" WHERE "drug_tests"."pact_id" = $1 [["pact_id", 1]]

 

Solution:

The problem was the ‘.first’ I was using at the end of the scope. It has triggered the later query

scope :next_up, -> {
  non_marked.where.not(scheduled_date: nil).
      where('scheduled_date > ?', DateTime.now).
      order(scheduled_date: :asc).
      limit(1)
}

Pact.find(1).drug_tests.next_up

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s