rzane/baby_squeel

[Error] Cannot use `joining` with `alias` on PostgreSQL

Closed this issue · 4 comments

Issue

I followed the joining with alias example

Course.joining{ enrollments.alias('e').on(id == enrollments.course_id) }

and received the following error:

  Course Load (2.4ms)  SELECT "courses".* FROM "courses" INNER JOIN "enrollments" "e" ON "courses"."id" = "enrollments"."course_id"
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  invalid reference to FROM-clause entry for table "enrollments"
LINE 1: ... INNER JOIN "enrollments" "e" ON "courses"."id" = "enrollmen...
                                                             ^
HINT:  Perhaps you meant to reference the table alias "e".
: SELECT "courses".* FROM "courses" INNER JOIN "enrollments" "e" ON "courses"."id" = "enrollments"."course_id"
from /var/lib/gems/2.3.0/gems/rack-mini-profiler-0.10.2/lib/patches/db/pg.rb:90:in `exec'

It looks like PostgreSQL requires that column of table inON condition must refer to that table alias if it's defined.

rzane commented

Yeah, currently, you'd have to write that query like this:

Course.joining{ enrollments.alias('e').on(id == enrollments.alias('e').course_id) }

But, I am working on a branch that allows you to write it like this:

Course.joining{ enrollments.alias('e').on { id == e.course_id } }

Thanks for the workaround. You should have it in the example doc.

rzane commented

Agreed! I'll work on that sometime this week.

I haven't had a chance to use this method until now. I'm afraid to say that this method doesn't work either. The query still refers to the original table name despite using alias.

Can you reopen this issue?