Last active
May 5, 2016 09:36
-
-
Save gamov/c761f0ac845f7bbbe002ad88e6d23cb8 to your computer and use it in GitHub Desktop.
ActiveRecord Queries Aliasing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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