Sunspot with multiple models (in Rails)
Asked Answered
B

1

14

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.

Backdate answered 17/5, 2011 at 22:15 Comment(1)
Did you end up creating new MVCs for your searcher?Interlocutory
P
23

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
Pulpiteer answered 17/5, 2011 at 22:42 Comment(2)
How to make an iteration over @sunspot_search instance variable in this situation? How to determine which result is User or Tag or Product?Aliciaalick
@Aliciaalick blog.obiefernandez.com/content/2012/01/…Pulpiteer

© 2022 - 2024 — McMap. All rights reserved.