Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Spree Decorator to add a custom ordering scope. Placed in "app/models/spree/product/"
Spree::Product.class_eval do
def self.simple_scopes
[
:ascend_by_random,
:ascend_by_updated_at,
:descend_by_updated_at,
:ascend_by_name,
:descend_by_name,
# Need to have master price scopes here
# This makes them appear in admin/product_groups/edit
:ascend_by_master_price,
:descend_by_master_price,
# :descend_by_popularity
]
end
simple_scopes.each do |name|
# We should not define price scopes here, as they require something slightly different
next if name.to_s.include?("master_price")
next if name.to_s.include?("random")
parts = name.to_s.match(/(.*)_by_(.*)/)
order_text = "#{Spree::Product.quoted_table_name}.#{parts[2]} #{parts[1] == 'ascend' ? "ASC" : "DESC"}"
self.scope(name.to_s, relation.order(order_text))
end
def self.ascend_by_random
order("RANDOM()")
end
end
@fabioaraujo121

This comment has been minimized.

Copy link

commented Apr 27, 2018

The scope has to be something callable.

So, your line 23, should be:

self.scope name.to_s, -> { relation.order(order_text) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.