Search code examples
ruby-on-railsrubysunspot-railssunspot-solr

Multi model search in sunspot rails


My model is

class Product < ActiveRecord::Base

has_many :category_products
has_many :categories , through: :category_products
has_many :product_tags
has_many :tags, through: :product_tags

I want to search all three models Category,Tags,Products.It works fine but issue I face is that when I search Category and Tag I want to get there related products.But how I differentiate when search only product column and when its associated tables.

My code is

@search = Sunspot.search[Product,Category,Tag] do
    fulltext params[:search]
    paginate(:page => params[:page] || 1, :per_page => 3)
  end
  @products = @search.results

At the end I want to get products.


Solution

  • Add 'categories' and 'tags' into your product search information like this:

    class Product < ActiveRecord::Base
      searchable do
        text :name
        text :categories do
          categories.map { |category| category.name }
        end
        text :tags do
          tags.map { |tag| tag.name }
        end
      end
    end
    
    @search = Sunspot.search(Product) do
      fulltext params[:search]
      paginate(:page => params[:page] || 1, :per_page => 3)
    end
    @products = @search.results
    

    link: https://github.com/sunspot/sunspot

    Hope this help!