[Feature request][ActiveRecord] Make inverse_of dynamic for the polymorphic belongs_to associations

When you have a few models which you would like to connect to the polymorphic model via has_one association and this associations named differently you have no option to tell belongs_to in the polymorphic model association how would you like to inverse_of for each specific polymorphic association.

Use case: PhoneNumber model which associates via belongs_to polymorphic association with different objects. Some of them have has_one :phone_number, and some of them have for example non-standard has_one :mobile_phone. In case if you would like to list all the phone numbers and get the belongs_to association with possibility of inversion, it throws an exception InverseOfAssociationNotFoundError.

Solution is to support possibility to set inverse_of with using Hash and/or Proc.

With Hash you can list all the connected classes and their inverse associations, like (this is preferred solution):

belongs_to :user,
          polymorphic: true,
          inverse_of: {'User': :phone_number, 'Company': :mobile_number}

Or using via Proc (it’s more dynamic) where you can detect what class currently is associated with a polymorphic model:

belongs_to :user,
           polymorphic: true, 
           inverse_of: -> klass { klass.is_a?(User) ? :phone_number : :mobile_number }

I’ve already tried to implement this functionality and it seems pretty easy to, just a few lines of code and a bit of tests.

Currently there are no solution to this issue at all, except to open a class and redefine a method.

1 Like