How to find out all the association of a model?

317 Views Asked by At

Say I have following models

class User < ApplicationRecord
  devise :database_authenticable,:registerable
         :recoverable, :trackable, :validatable, :rememberable
  
  belongs_to :loginable, polymorphic: true
end

class Customer < ApplicationRecord
  has_one :user, as: :loginable, dependent: :destroy
end

There are many models similar to Customer. How do I find out all such models from User model itself? I tried User.reflections. But it does not show the association with Customer. Is there a method say User.relationships that will list Customer and all models similar to Customer? If not how can I go about find out such models?

2

There are 2 best solutions below

0
Siim Liiser On BEST ANSWER

If the question is to look for all classes that User can belong to, then that's literally every model in your code. This is what polymorphic does.

If the question is what models User currently belongs to, then use the database to figure it out.

User.distinct.pluck(:loginable_type)

If the question is what models define a has_one :user relationship, then you'll have to look through all the models and ask that question from their perspective using the .reflections method you already found.

0
Vasfed On

belongs_to :loginable, polymorphic: true yields loginable_id and loginable_type (contains class name) fields in User model. Linked model does not have to have reverse relation, so you can only find such models by carefully examining the code.

Also production data may contain links to models that already are not present in application at all (were deleted from app, but not from data, fetching these result in an error), get User.distinct.pluck(:loginable_type) from your production for a list of used ones (but because of above - list is not guranteed to be complete).