Skip to content

Instantly share code, notes, and snippets.

@berkes
Created February 28, 2012 10:36
Show Gist options
  • Select an option

  • Save berkes/1931810 to your computer and use it in GitHub Desktop.

Select an option

Save berkes/1931810 to your computer and use it in GitHub Desktop.
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
Copy link
Copy Markdown

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