Search code examples
ruby-on-rails-4solrsunspot

Filter sunspot search by class


I've set up a sunspot/solr search with rails that works like a charme:

# run the search
search_results = Sunspot.search Project, Question, User, Requests do
  fulltext params[:search]

  paginate page: params[:page], per_page: 10
end

It could be cool to filter that search results by a given class. E.g.there is a param in the URL like params[:class], it would be awesome if the search would only consist of results from that specific class (Project, Question, User, Requests...).

I just can't figure out where to start at.

Hope someone could help me out!


Solution

  • Got it. All you need to do is adding the class as a string to the searchable block:

    # solr search
    searchable do
      text :firstname, :lastname, :email, :position
      integer :account_id
      string :klass
    end
    
    def klass
      return self.class.to_s.downcase
    end
    

    After that you're able to filter by the class (klass)

    # run the search
    search_results = Sunspot.search Project, Question, User do
      fulltext params[:search]
      with :account_id, params[:account_id]
      with :klass, "question"
    
      paginate page: params[:page], per_page: 10
    end