Last Updated: December 30, 2017
·
9.462K
· zentralmaschine

Polymorphic associations and Single Table Inheritance

If you want to use polymorphic associations on your STI models you have to make sure to tell the polymorphic model to store the base type as the type of the belonging model and not the actual type.

Example:

class Person < ActiveRecord::Base
  has_many :images, as: :imageable
end

class Celebrity < Person
end

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end

Now, if you add an image to Person everything works just fine. But try adding an image to Celebrity model and suddenly nothing works anymore. What actually will happen, is that the imageable_type will be set to Celebrity, but when you want to retrieve a Celebrity models images, ActiveRecord will query for an image with an imageable_type of Person and that simply does not exist.

As said above, in order to fix this you have to always store the base class as imageable_type, which can be advised like so:

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true

  def imageable_type=(sType)
    super(sType.to_s.classify.constantize.base_class.to_s)
  end
end

Read more about it in the Rails API.

Why this does not work out of the box is beyond me...

1 Response
Add your response

I'm on Rails 5.1.4 and this seems to work OOTB now.

over 1 year ago ·