mrkamel/search_cop — pull request #10 by jetaggart (2014-12-23 02:05:09+00:00)
Title: Join fails on complex polymorphic associations

Get ready, cause this ones a doozy. I have a polymorphic association that I'm trying to do searches on. I've written a test case that shows the incorrect behavior `polymorphic_test.rb`.

The issue is the SQL generated is wrong. The query builder generates this statement:

``` sql
SELECT "accounts"."id" AS t0_r0,
"text_shouts"."id" AS t1_r0,
"text_shouts"."text" AS t1_r1,
"picture_shouts"."id" AS t2_r0,
"picture_shouts"."url" AS t2_r1
FROM "accounts"
LEFT OUTER JOIN "shouts"
ON "shouts"."account_id" = "accounts"."id"
AND "shouts"."content_type" = 'TextShout'
LEFT OUTER JOIN "text_shouts"
ON "text_shouts"."id" = "shouts"."content_id"
LEFT OUTER JOIN "shouts" "shouts_accounts_join"
ON "shouts_accounts_join"."account_id" = "accounts"."id"
AND "shouts"."content_type" = 'PictureShout'
LEFT OUTER JOIN "picture_shouts"
ON "picture_shouts"."id" =
"shouts_accounts_join"."content_id"
WHERE (( "text_shouts"."text" LIKE '%some%'
OR "picture_shouts"."url" LIKE '%some%' ))
```

Notice the second join to the `shouts` table for `PictureShout`. It uses the correct aliased table `shouts_accounts_join` for the `id` comparison, but uses the original table name `shouts` instead of the alias for the second comparison `content_type`.

Digging through the source, I feel like this may be a bug in arel itself, but I'm not sure. Any help would be appreciated! Sorry for such a complex issue, I don't know how to show it more simply.