lundi 7 novembre 2022

OPTIMIZE QUERY ON RAILS - POSTGRESQL

I have 3 scopes: 1 - lists the promotions in progress. 2 - sort out of stock last 3 - list the promotions that are not in progress.

Is it possible to combine everything in a single scope? It would be: List the promotions in progress, in order of stock from highest to lowest, and then the promotions that are not in progress.

I tried, but I couldn't.

scope :in_progress, -> { start_and_end_dates.in_weeks.between_hours }
    
scope :without_stock_last, lambda {
  select('promotions.*, (CASE WHEN offers.current_inventory > 0 THEN 1 ELSE 0 END) AS "is_available"')
   .order('is_available DESC')
   .group('promotions.id, offers.current_inventory, offers.created_at')
}
    
scope :not_progress, lambda {
  promotions_in_progress = Promotion.in_progress.pluck(:id).join(",")
  Promotion.with_estabilishment.select("promotions.*, (CASE WHEN promotions.id NOT IN (#{promotions_in_progress}) THEN 0 END) AS is_unavailable")
  .order('is_unavailable DESC')
}

Aucun commentaire:

Enregistrer un commentaire