0

I am learning some Solidus (fork of Spree). I built the sandbox following the readme

Now i want to add a scope in Product to build a query that sorts products evaluating every variant. For each product i want to evaluate the lowest variant price of every product.

For instance, if i have three products

a.price = 2
b.price = 3
c.price = 4

a and b have only master variant, c has two variants

c.variants.first.price = 4
c.variants.last.price = 1

the ordered products should be

c, a, b

I managed to do this in the home#index working with arrays, but i broke the cache(cache_key_for_products) in home/index.html.erb method.

So i would like to do the same thing, but using ActiveRecord_Relation

I don't know how to build a good query with rails and solidus, any help would be appreciated.

1 Answers1

0

Hope this might be helpful for you.

class Product < ApplicationRecord 
 has_many :variants,  dependent: :destroy
end

class Variant < ApplicationRecord
belongs_to :product
end


def index
 @products = Product.left_outer_joins(:variants).order("case when variants.id is null then products.price else variants.price end asc")
end