about

writing

contact

Model Specific Formatted Search Results Using Thinking Sphinx

By eric

2010-02-08

Having recently implemented Thinking Sphinx on one of my web sites, I thought it would be cool to be able to search every indexed model. With Thinking Sphinx, it’s easy to have a bunch of different classes returned in the results. The tougher part is displaying them in a way that is organized (although admittedly not very DRY).
Let’s start out with the controller method for search results (app/controllers/search_controller.rb):

The interesting thing about this bit of code is the eval. The eval on each iteration decides which search result partial to display based on the class and then passes the result to the partial for display. So if the result has a class of Business, the partial app/views/businesses/_result.html.erb will be rendered. This is a quick example of a search result partial:

This is useful because all models don’t have the same characteristics. By creating a search result partial for each model type, this can be reused for consistent looking search results around your webapp. If the search is model specific, the same result partial will be used in every iteration over the results. If the search is model agnostic, then you can display your search results in a consistent manner.

Hi Ben… thanks for this post… it looks very helpful and I’m eager to try implementing it in my app. Can you offer any details on your search box/form itself, and how you hook it up with your search_controller? In particular:nn*how is :model passed back through the params hash? Could I use that approach if I have a dropdown next to my search box that, for example, lets the user choose to search either the “projects” or “updates” models?nn*how are the keywords in the search query passed? Do you just have a search form with form_tag placed in a partial? Which view holds that form?nnMost of the search implementations I’ve found seem to have search reside within the index action of a particular controller/model, so I found yours particularly valuable since I’m interested in search across several models at once.nnThanks,nnDean RichardsonnGenlighten.comnn