Last Updated: February 25, 2016
·
1.006K
· pierre-o

Polymorphic index? No problems!

If you use thinking-sphinx, this is a nice trick if you need to index polymorphic attributes.

In our case, we have questions that could belong to campaigns or startups. So those questions are polymorphic. But we still need to index them. Here is the description of the index in pure SQL:

  indexes "CASE questions.subject_type 
    WHEN 'Campaign' THEN (
      SELECT campaigns.name
      FROM campaigns
      WHERE campaigns.id = questions.subject_id
    )
    WHEN 'Startup' THEN (
      SELECT startups.name
      FROM startups
      WHERE startups.id = questions.subject_id
    )
    END", :as => :startup
````

Thanks [@pedrocarrico](twitter.com/pedrocarrico)!