[Feature Request] Allow Polymorphic Assocation Type to be a Belongs To Association Itself

My understanding of polymorphic associations is you have a an id column and a type column (which must be a model name):

attachable_id [Integer]

attachable_type [String]

class Asset < ActiveRecord::Base belongs_to :attachable, polymorphic: true end

class Post < ActiveRecord::Base has_many :assets, as: :attachable end

``

While this is nice in terms of simplicity, it can be somewhat limiting.

I would like the option to have my type column be an id pointing to another model, that could have the class name as column there:

attachable_id [Integer]

attachable_type_id [Integer]

class Asset < ActiveRecord::Base belongs_to :attachable_type belongs_to :attachable, polymorphic: true end

class Post < ActiveRecord::Base has_many :assets, as: :attachable end

model_name [String]

class AttachableType < ActiveRecord::Base end

``

The advantages for me are:

  • Model name changes only need to happen in one place in the db
  • The ability to add a foreign key constraint on type column
  • Use up less space with an integer column instead of a text one I’m currently working on a moderately large Rails app that uses a lot of single-table inheritance, and am looking to replace it with polymorphism.

While I can do that with the existing functionality, abstracting my list of types into its own table (with extra metadata) would add a lot of convenience.

Please let me know if this sounds reasonable.