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…

Share this: