When Ultrasphinx is used with polymorphic associations…
Lets first consider simple has_many and belongs_to associations as:
Now if you wish to index the title of associated article with comment for searching, you just need to add ” is_indexed :fields => :body, :include => [{ :association_name => ‘article’, :field => ‘title’, :as=> ‘article_title’}] ”
So, your comment model will look like:
Setup ultrasphinx by issuing:
Now at rails console try:
Simple, we have article and comment models with has_many belongs_to associations. Comments are indexed with their associated article title. So it can return comments if query matches with article’s titles.
Now, consider a case when we wish to change comment model to make it polymorphic. In that case our models will be look like:
Check at rails if associations are working fine:
Now, the point is to index article title with comments. Here we can get associated article using ‘commentable’ i.e. comment.commentable.
So, change ultrasphinx is_indexed code in comment model accordingly:
Note that we have changed associan_name to ‘commentable’.
Next, when we reconfigure ultrasphinx using ” rake ultrasphinx:bootstrap”(since we have changed db schema), it starts throwing errors:
After spending some time on research, I was able to make it work by making some changes in comment model:
Lets check it on rails console:
In such cases we need to define class_name and association_sql in is_indexed statement instead of association_name.
Hope it helps…


Working with Vinsol has been one of the most rewarding and productive collaborations I've ever had in the technology industry. Manik is an intelligent and honest engineer with a great faculty for open and clear communication, and his team include some of the swiftest and keenest developers I've ever had the pleasure to work with. They're great value for money, excellent people who are a joy to know and interact with, and above all they really know their stuff