How do I get all associated models from an ActiveRecord object?

For example, I have

class Order < ActiveRecord::Base
  has_many :shippings
  has_one :contact_information
  belongs_to :shop
end

      

How to get an array of related objects from Order. for example

Order.associations
# [:shipping, :contact_information, :shop]

      

+3


source to share


1 answer


Order.reflect_on_all_associations.map(&:class_name)

      

You can pass the type of the relationship as a parameter: Order.reflect_on_all_associations(:has_one)

Read about ActiveRecord :: Reflection :: ClassMethods

EDIT



Just realized you asked about object-associated models.

So, with what I have already shown, you can simply do something along the following lines:

@some_order = Order.first
associated_models = @some_order.class.reflect_on_all_associations.map(&:class_name)

      

+5


source







All Articles