rails/rails — pull request #14154 by al2o3cr (2014-02-22 00:33:19+00:00)
Title: Pass a base relation to build_default_scope when joining

This PR fixes the problem noted in #12770 where the clause added by the `default_scope` did not correctly pick up the aliased table name (causing the condition to be on `"categorizations"."special"` instead of `"special_categorizations_categories"."special"`). This is apparently an error on some versions of Postgres, but produces incorrect results even when it can be successfully executed.

Before this patch, the SQL generated in the added test case is:
```
SELECT "categories"."id" AS t0_r0, "categories"."name" AS t0_r1, "categories"."type" AS t0_r2, "categories"."categorizations_count" AS t0_r3, "categorizations"."id" AS t1_r0, "categorizations"."category_id" AS t1_r1, "categorizations"."named_category_name" AS t1_r2, "categorizations"."post_id" AS t1_r3, "categorizations"."author_id" AS t1_r4, "categorizations"."special" AS t1_r5 FROM "categories"
LEFT OUTER JOIN "categorizations" "special_categorizations_categories"
ON "special_categorizations_categories"."category_id" = "categories"."id"
AND "categorizations"."special" = 't'
INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id"
WHERE "categorizations"."author_id" = ?
```
After the patch, the SQL is (mostly) correct:
```
SELECT "categories"."id" AS t0_r0, "categories"."name" AS t0_r1, "categories"."type" AS t0_r2, "categories"."categorizations_count" AS t0_r3, "categorizations"."id" AS t1_r0, "categorizations"."category_id" AS t1_r1, "categorizations"."named_category_name" AS t1_r2, "categorizations"."post_id" AS t1_r3, "categorizations"."author_id" AS t1_r4, "categorizations"."special" AS t1_r5 FROM "categories"
LEFT OUTER JOIN "categorizations" "special_categorizations_categories"
ON "special_categorizations_categories"."category_id" = "categories"."id"
AND "special_categorizations_categories"."special" = 't'
INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."author_id" = ?
```

The SQL is only "mostly correct" because the `SELECT` isn't picking up the table alias and results in incorrect data loaded into `special_characterizations` (both before and after the patch). I'll open a separate issue for that.

/cc @tenderlove