ActiveRecord, has_many :through, and Polymorphic Associations

There is a known issue with Rails 3.1.1 that breaks this functionality. If you are having this problem first try upgrading, it’s been fixed in 3.1.2

You’re so close. The problem is you’re misusing the :source option. :source should points to the polymorphic belongs_to relationship. Then all you need to do is specify :source_type for the relationship you’re trying to define.

This fix to the Widget model should allow you do exactly what you’re looking for.

class Widget < ActiveRecord::Base
  has_many :widget_groupings

  has_many :people, :through => :widget_groupings, :source => :grouper, :source_type => 'Person'
  has_many :aliens, :through => :widget_groupings, :source => :grouper, :source_type => 'Alien'
end

Leave a Comment