Search code examples
ruby-on-railsruby-on-rails-3searchsolrsunspot

How can I search across multiple tables(models) with Sunspot Solr?


I want users to be able to use one search box to search for different objects. I would differentiate them on the results page. Both would be full text search.

Should I make a Search controller and load everything into the index action with something like:

@posts = Post.all
@groups = Group.all

Something tells me that would be fantastically inefficient.

I'm not really sure where to start, I haven't managed to find anything addressing this question on the interwebs, but if I have overlooked something let me know.

Thanks

EDIT: here's my search bar that is available globally on my website:

    -form_tag posts_path, :method => :get do
     =text_field_tag :search, params[:search], :id => 'searchfield'
     =submit_tag '',:name => nil, :id => 'searchbutton'

it only searches the "Post" model right now, and displays the results on the Post#index view

I want to be able to have queries typed into the search box be searched for in both the Post and Group tables, and the results be displayed in two separate columns on the same page. maybe through a search controller/view


Solution

  • Add the searchable directive from sunspot solr to your models for indexing. For example:

    class Post < ActiveRecord::Base
      searchable do
        text :title, :body
      end
    end
    
    class Group < ActiveRecord::Base
      searchable do
        text :name
      end
    end
    

    If you have existing data in DB make sure to run rake sunspot:solr:reindex for indexing. For new data the indexing will be done in a hook.

    Now you can search:

    @posts = Post.search {fulltext params[:search]}
    @groups = Group.search {fulltext params[:search]}
    

    Now you have the data for your two columns.