Dumb and Cheap Hack for Product Filter in Spree

Spree: Feeling lazy, here is how to build easy Product Filters

Posted by @krazedkrish on January 27, 2016

Disclaimer:

This is not a standard way to create product filter. But its quick and it works.

If you want to follow the standard follow this sample/guide.

Quick tricks for Product Filter

Here is how to do it:

1. create /lib/spree/custom_search.rb file in your project folder

2. add require "#{Rails.root}/lib/spree/custom_search" to /config/initializers/spree.rb

3. create the module for ProductFilters

module Spree
  module Core
    module ProductFilters

    ...
    # your search scopes here
    ...

    end
  end
end

4. add the search scopes required.

module Spree
  module Core
    module ProductFilters

    # example scope
    # may be you guys can opitmize/shorten 2 queries in 1
    # I will be glad, if you include it in comments
    Spree::Product.add_search_scope :in_taxonomy do |taxonomy|
      taxons=Spree::Taxonomy.includes(taxons: :products).where(:id=>taxonomy).select(:id).map &:taxon_ids
      taxons=taxons.flatten

      # the line below will be concatinated to the select query for the product
      # so you dont have to with "Spree::Product..."
      in_taxons(taxons)
    end

    end
  end
end

Again, this is not a standard approach. But If all you need is to add one line why follow the standard Product Filter. Standards are to ease the development time. What if! not following the standards does less harm and more good, I say:

“Be agile and lazy! Be awesome!!”

You dont agree with me. No Problem! Here are some useful reference for you for building standard ones.