【问题标题】:How to get all the associated models from ActiveRecord object?如何从 ActiveRecord 对象中获取所有关联模型?
【发布时间】:2014-11-19 12:34:19
【问题描述】:
例如我有
class Order < ActiveRecord::Base
has_many :shippings
has_one :contact_information
belongs_to :shop
end
如何从 Order 中获取关联对象的数组。例如
Order.associations
# [:shipping, :contact_information, :shop]
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-4
activerecord
ruby-on-rails-5
ruby-on-rails-6
【解决方案1】:
Order.reflect_on_all_associations.map(&:class_name)
您可以将关系类型作为参数传递:
Order.reflect_on_all_associations(:has_one)
了解ActiveRecord::Reflection::ClassMethods
编辑
刚刚意识到,您已经询问了对象的关联模型。
因此,有了我已经展示过的内容,您可以简单地按照以下方式进行操作:
associated_models = Order.reflect_on_all_associations.map(&:class_name)