Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sunspot with multiple models (in Rails)

I have three models (User, Tag, Product) and they interact s.t. User has many Tags and Products.

For searching purposes, I would like to be able to search (with one search bar) on user names, tag names, and product descriptions. I would also like to search on product pages, but that is only relevant for tag names and product descriptions.

Here are two examples:

Search: "Linus Torvalds" returns all instances of Linus Torvalds in the three models with any instances of the user name being placed higher.

Search: "Linux" with age: "20-25" returns all instances of Users with Products that include "Linux" in their name/description and fall in that age range, as well as Users with tags that include "Linux" and who have Products that fall in that age range. Note that if the search didnt include the age, then it would default to all who fit the "Linux" part rather than none.

My question is what would be the best way of doing this? Should I create a search model with its own controller? Should I just ignore that and include a search partial in a shared folder? What other methods are there?

Thanks much.

like image 218
user592419 Avatar asked May 17 '11 22:05

user592419


1 Answers

I like the idea of a Search object if you are doing any complicated conditions.

But to search across objects using Sunspot:

@sunspot_search = Sunspot.search User, Tag, Product do |query| 
  query.keywords @search_query
  query.with(:age).greater_than 20
  query.with(:age).less_than 25
  query.paginate(:page => params[:page], :per_page => 30)
end
like image 136
Jesse Wolgamott Avatar answered Oct 14 '22 22:10

Jesse Wolgamott