Skip to content

Instantly share code, notes, and snippets.

@gamov
Last active May 5, 2016 09:36
Show Gist options
  • Save gamov/c761f0ac845f7bbbe002ad88e6d23cb8 to your computer and use it in GitHub Desktop.
Save gamov/c761f0ac845f7bbbe002ad88e6d23cb8 to your computer and use it in GitHub Desktop.
ActiveRecord Queries Aliasing
# Rails 4.0.13
items = ShippingItem.joins(shipment: :booking)
.joins("INNER JOIN (#{
ShippingItem.joins(shipment: :booking).select('max(booking.eta), shipment.dest_site_id').group('shipments.dest_site_id').to_sql
}) AS sub sub.dest_site_id = shipments.dest_site_id AND booking.eta = sub.max_eta")
.order(Shipment.arel_table[:dest_site_id])
# The outer query tables get automagically aliased (`shipments` `shipments_shipping_items`, `shipment_bookings` `shipment_bookings_shipments`)
# because they are present in the inner subquery (even though isolated by parenthesis!) but this makes referencing fails because
# of the alias (Shipment.arel_table[:dest_site_id] => shipments.dest_site_id instead of shipments_shipping_items.dest_site_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment