Skip to content

Instantly share code, notes, and snippets.

@gamov
Last active December 11, 2015 11:18
Show Gist options
  • Save gamov/4592607 to your computer and use it in GitHub Desktop.
Save gamov/4592607 to your computer and use it in GitHub Desktop.
@search= ShippingItem.joins(:shipment => {:shipment_booking => {:dest_place => :address}}).
departed.
merge(Shipment.with_check_price_done).
merge(Shipment.eta_in_prev_months 12).
where(:unit_check_price.gt => 0).
select('MAX(shipment_bookings.eta) AS latest_eta, shipping_items.item_variant_id AS latest_iv_id, addresses.country AS latest_country').
group('shipping_items.item_variant_id, addresses.country').
search(params[:search])
@subquery = @search.relation.to_sql
@shipping_items = ShippingItem.joins(:shipment => {:shipment_booking => {:dest_place => :address}}).
joins("JOIN (#{@subquery}) ON item_variant_id = latest_iv_id AND eta = latest_eta AND country = latest_country").
order_by_family_iv.
includes(:item_variant => {:item_family => :category}, :shipment => [:forex_rates_bundle, :shipment_booking => {:dest_place => :address}]).
page(params[:page])
@gamov
Copy link
Author

gamov commented Oct 30, 2013

I think we can just extract the shipping_item_ids from the subquery then just load them with second query. Adding an having clause should also yield the proper result without the need of a subquery...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment