public
Last active

OptionValue filter

  • Download Gist
product_filters.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
def ProductFilters.option_with_values(option_scope, option, values)
# get values IDs for Option with name {@option} and value-names in {@values} for use in SQL below
option_values = Spree::OptionValue.where(:presentation => [values].flatten).joins(:option_type).where(OptionType.table_name => {:name => option}).pluck("#{OptionValue.table_name}.id")
return option_scope if option_values.empty?
 
option_scope = option_scope.where("#{Product.table_name}.id in (select product_id from #{Variant.table_name} v left join spree_option_values_variants ov on ov.variant_id = v.id where ov.option_value_id in (?))", option_values)
option_scope
end
 
# option scope
Spree::Product.scope :option_any,
lambda { |*opts|
option_scope = Spree::Product.includes(:variants_including_master)
 
opts.map { |opt|
# opt is an array => ['option-name', [value1, value2, value3, ...]]
option_scope = option_with_values(option_scope, *opt)
}
option_scope
}
 
# size option
def ProductFilters.size_filter
sizes = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("briefs-size")).order("position").map(&:presentation).compact.uniq
{
:name => "Size",
:scope => :option_any,
:conds => nil,
:option => 'briefs-size', # this is MANDATORY
:class => "sizes",
:labels => sizes.map { |k| [k, k] }
}
end
 
# model option
def ProductFilters.model_filter
models = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("briefs-model")).order("position").map(&:presentation).compact.uniq
{
:name => "Model",
:scope => :option_any,
:conds => nil,
:option => 'briefs-model', # this is MANDATORY
:class => "model",
:labels => models.map { |k| [k, k] }
}
end
 
# color option
def ProductFilters.color_filter
colors = Spree::OptionValue.where(:option_type_id => Spree::OptionType.find_by_name("briefs-color")).order("position").map(&:presentation).compact.uniq
{
:name => "Color",
:scope => :option_any,
:conds => nil,
:option => 'briefs-color', # this is MANDATORY
:class => "color",
:labels => colors.map { |k| [k, k] }
}
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.