diff --git a/core/app/models/spree/product/scopes.rb b/core/app/models/spree/product/scopes.rb index 6daa94c35b3..bcaeac5824a 100644 --- a/core/app/models/spree/product/scopes.rb +++ b/core/app/models/spree/product/scopes.rb @@ -158,7 +158,7 @@ def self.property_conditions(property) # order: 'COALESCE(cnt, 0) DESC' add_search_scope :descend_by_popularity do joins(:master). - order(%{ + order(Arel.sql(%{ COALESCE(( SELECT COUNT(#{Spree::LineItem.quoted_table_name}.id) @@ -171,7 +171,7 @@ def self.property_conditions(property) WHERE popular_variants.product_id = #{Spree::Product.quoted_table_name}.id ), 0) DESC - }) + })) end add_search_scope :not_deleted do diff --git a/core/spec/models/spree/product/scopes_spec.rb b/core/spec/models/spree/product/scopes_spec.rb index e5699e320ec..85716e9e532 100644 --- a/core/spec/models/spree/product/scopes_spec.rb +++ b/core/spec/models/spree/product/scopes_spec.rb @@ -116,6 +116,17 @@ end end + context "descend_by_popularity" do + let!(:variant_1) { create(:master_variant) } + let!(:variant_2) { create(:master_variant) } + + let!(:line_item_1) { create(:line_item, variant: variant_1, quantity: 3) } + let!(:line_item_2) { create(:line_item, variant: variant_2, quantity: 2) } + it "orders products by popularity" do + expect(Spree::Product.descend_by_popularity.map(&:id)).to eq([variant_1.product.id, variant_2.product.id, product.id]) + end + end + describe '.available' do context "a product with past available_on" do let!(:product) { create(:product, available_on: 1.day.ago) }