Modifying polymorphic type in rails

2024-07-03

Rails allows you to define polymorphic associations easily by defining polymorphic: true on a reference in your migration. Doing this will create two new columns *_type and *_id. And you can reference them like:

class Record < ActiveMigration[7.1]
	def something
		# do something
	end
end

And use them like:

Rails sets the type to the CamelCased name of the associated Active Record class by default and changing that (even to kebab case) will result in an error. So if your model was namespaces ex. Namespace::Something, the type would be NamespaceSomething and you may not want that.

To change this you need to set the polymorphic name in the associated model:

And define class mappings for the new name in the base model: