Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the associated models from 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 associated objects from Order. For example

Order.associations
# [:shipping, :contact_information, :shop]
like image 827
Maxim Abramchuk Avatar asked Nov 19 '14 12:11

Maxim Abramchuk


1 Answers

Order.reflect_on_all_associations.map(&:class_name)

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

Read about ActiveRecord::Reflection::ClassMethods

EDIT

Just realised, you've asked about object's associated models.

So, having what I've already shown, you can simply do something along the following lines:

associated_models = Order.reflect_on_all_associations.map(&:class_name)
like image 186
Andrey Deineko Avatar answered Oct 13 '22 00:10

Andrey Deineko