Search Multiple Models at Once with Thinking Sphinx

Buried in the Thinking Sphinx documentation I found a powerfully easy answer to a problem that is otherwise not easy to solve with ActiveRecord. How do you search across multiple models and combine the results into a single set without individually querying each model and melding the results together manually?

One way we have done this is through a union query in a find_by_sql, which works well enough to query multiple tables but only returns results of a single type, unless you refactor ActiveRecord to instantiate different models depending on the type (which we did in this case).

With Thinking Sphinx it’s as simple as this: "term", :classes => [Post, User, Photo, Event]

And the result comes back with a neatly instantiated combination of posts, users, photos, and events.

Is this more efficient than the previous method? I do not know, I will have to check.

February 26, 2009 in Ruby on Rails