Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Last active August 29, 2015 14:01
Show Gist options
  • Save jcoglan/fa01e62062ed64900c55 to your computer and use it in GitHub Desktop.
Save jcoglan/fa01e62062ed64900c55 to your computer and use it in GitHub Desktop.

If you have these classes:

class Foo < ActiveRecord::Base
  has_many :things, as: :content
end

class Bar < Foo
end

class Thing < ActiveRecord::Base
  belongs_to :content, polymorphic: true
end

Then assigning a Bar to thing.content then Rail sets thing.content_type to 'Foo'.

>> thing = Thing.new
>> bar = Bar.new
>> thing.content = bar
>> thing.content_type
=> "Foo"

Can you make Rails use the actual type of a polymorphic object as the type key, rather than the type of the object's superclass?

@chrisroos
Copy link

What happens if you redefine the has_many on Bar? Not ideal, but I wonder if it even works.

@elskwid
Copy link

elskwid commented May 16, 2014

@jcoglan, I remember seeing this but am drawing a blank on the solution. I feel like the answer is in here: https://github.com/rails/rails/blob/6ef0569b0bf6e13d63f6c51790745b2007b92973/activerecord/lib/active_record/inheritance.rb

Here's a test similar to yours: https://github.com/rails/rails/blob/0bccde963c0b3e2ad65b2bdac9d144f40854ec90/activerecord/test/cases/associations/belongs_to_associations_test.rb#L130 it looks like the behavior you're seeing is expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment