如何从ActiveRecord对象获取所有关联的模型? [英] How to get all the associated models from ActiveRecord object?

查看:77
本文介绍了如何从ActiveRecord对象获取所有关联的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有

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

如何从Order获取关联对象的数组.例如

How to get an array of associated objects from Order. For example

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

推荐答案

Order.reflect_on_all_associations.map(&:class_name)

您可以将一种关系类型作为参数传递: Order.reflect_on_all_associations(:has_one)

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

了解 ActiveRecord :: Reflection :: ClassMethods

刚意识到,您已经询问了对象的关联模型.

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)

这篇关于如何从ActiveRecord对象获取所有关联的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆