How to get all the associated models from ActiveRecord object?

折月煮酒 提交于 2020-06-25 04:51:48

问题


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]

回答1:


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 showed, 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)


来源:https://stackoverflow.com/questions/27016957/how-to-get-all-the-associated-models-from-activerecord-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!