ruby-on-railsrelationshippolymorphic-associationsmodel-associationsrails-models

How to find out all the association of a model?


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?


Solution

  • 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.