[英]Add multiple filters in Spree Commerce Rails
We need to implement custom filters for categories in spree ecommerce in latest version as seen here https://github.com/spree/spree . 我们需要在最新版本的Spree电子商务中为类别实现自定义过滤器,如https://github.com/spree/spree所示 。
We need to do it in a dynamic way because we have about 100 filters or more to make. 我们需要以动态方式进行操作,因为我们要制作大约100个或更多的过滤器。 The ideal solution would be to show all available filters in admin area and admin can activate/deactivate them for each category. 理想的解决方案是在管理区域中显示所有可用的过滤器,并且管理员可以为每个类别激活/停用它们。
Current Scenario: We know how to make a new filter and apply it. 当前方案:我们知道如何制作一个新的过滤器并应用它。 But it takes about four methods per filter as shown in the product_filter.rb file linked below. 但是每个过滤器大约需要四种方法,如下面链接的product_filter.rb文件所示。
Some links we have found useful: 我们发现一些有用的链接:
https://gist.github.com/maxivak/cc73b88699c9c6b45a95 https://github.com/radar/spree-core/blob/master/lib/spree/product_filters.rb https://gist.github.com/maxivak/cc73b88699c9c6b45a95 https://github.com/radar/spree-core/blob/master/lib/spree/product_filters.rb
Here is some code that allows you to filter by multiple properties. 这是一些代码,使您可以按多个属性进行过滤。 It is not ideal (no proper validation etc) but I guess it is better than doing multiple "in" subqueries. 这是不理想的(没有适当的验证等),但我想它比执行多个“ in”子查询要好。
def add_search_scopes(base_scope)
joins = nil
conditions = nil
product_property_alias = nil
i = 1
search.each do |name, scope_attribute|
scope_name = name.to_sym
# If method is defined in product_filters
if base_scope.respond_to?(:search_scopes) && base_scope.search_scopes.include?(scope_name.to_sym)
base_scope = base_scope.send(scope_name, *scope_attribute)
else
next if scope_attribute.first.empty?
# Find property by name
property_name = name.gsub('_any', '').gsub('selective_', '')
property = Spree::Property.find_by_name(property_name)
next unless property
# Table joins
joins = product if joins.nil?
product_property_alias = product_property.alias("filter_product_property_#{i}")
joins = joins.join(product_property_alias).on(product[:id].eq(product_property_alias[:product_id]))
i += 1
# Conditions
condition = product_property_alias[:property_id].eq(property.id)
.and(product_property_alias[:value].eq(scope_attribute))
conditions = conditions.nil? ? condition : conditions.and(condition)
end
end if search.is_a?(Hash)
joins ? base_scope.joins(joins.join_sources).where(conditions) : base_scope
end
def prepare(params)
super
@properties[:product] = Spree::Product.arel_table
@properties[:product_property] = Spree::ProductProperty.arel_table
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.