Question

Here is a query for ambiguous columns in two joined tables:

SELECT
  o.time as order_time,
  c.time as client_time
FROM
  orders o
  INNER JOIN clients c ON c.id = o.client_id

when doing the same in ActiveRecord query language, all the sources suggest something like this:

Order.select('orders.time as order_time, c.time as client_time').joins(:client)

What I do not like here is the part:

.select('orders.time as order_time, c.time as client_time')

I would prefer to use ActiveRecord syntax, something like this:

.select(order: { time: 'order_time' }, client: { time: 'client_time'})

Does something similar exist in Rails?

Was it helpful?

Solution

Unfortunately there's no clean ActiveRecord way to do what you want that I know of. But you can always try ARel:

Order.joins(:client).select([
  Order.arel_table[:time].as('order_time'),
  Client.arel_table[:time].as('client_time')
])

This produces the SQL you posted (sans the shorter names for tables), and works for rails 3+ < 4. In rails 4 you can ditch the square parentheses from the select method. Do note that this is ActiveRecord combined with ARel, and not ARel only.

Full code for ARel would look as follows:

o = Order.arel_table # or Arel::Table.new('orders')
c = Client.arel_table

o.project(o[:time].as('order_time'), c[:time].as('client_time')).join(c).on(c[:id].eq(o[:client_id]))
# => SELECT "orders"."time" AS order_time, "clients"."time" AS client_time FROM "orders" INNER JOIN "clients" ON "clients"."id" = "orders"."client_id"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top