mardi 25 décembre 2018

Active records/SQL: find options at data point closest to limit

I am working on a shipping cost routine. I have a cart, cart_items and shippingservice model. I know length, width, height and weight of all cart_items and calculated the accumulated weight + height and found the max length + width for the shipment.

I have in my cart model a method which already takes weight, height and carrier into account

# Methods shippingservices
def available_shipping_services
  Shippingservice.where('weightmin <= ? and weightmax >= ?', total_weight, total_weight).where('height >= ?', total_height).where('length >= ?', max_length).where('width >= ?', max_width).where('shippingservices.shippingcarrier = ?', '1') 
end

The problem I have is that the shipping carrier has standard and express shipments for different sizes (compact and large).

International compact M 381mm length, 305mm width, 20mm height, 51-100gr

International large S 450mm length, 450mm width, 240mm height, 1-350gr

Int. Priority compact M 381mm length, 305mm width, 20mm height, 51-100gr

Int. Priority large S 450mm length, 450mm width, 240mm height, 1-350gr

There are a few cases where both compact and large options overlap and are displayed together and I end up with 4 options where the closest option in size as standard and priority would be enough.

For the 4 examples above I would get 4 options when the cart would weigh below 100gr, have height below 20mm and be smaller than 381x305mm.

I would like to find an active records or sql query, which would exclude the superfluous options and only displayed the closest ones.

Something like: take all shippingservice entries which respect weight and height, for the integer value point closest to cart width/length.

How can I achieve this?

Thank you very much in advance!

Aucun commentaire:

Enregistrer un commentaire