簡體   English   中英

如何從 ActiveRecord 對象獲取所有關聯的模型?

[英]How to get all the associated models from ActiveRecord object?

例如我有

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

如何從 Order 獲取關聯對象的數組。 例如

Order.associations
# [:shipping, :contact_information, :shop]
Order.reflect_on_all_associations.map(&:class_name)

您可以將一種關系類型作為參數傳遞: Order.reflect_on_all_associations(:has_one)

閱讀ActiveRecord::Reflection::ClassMethods

編輯

剛剛意識到,您已經詢問了對象的關聯模型。

因此,根據我已經展示的內容,您可以簡單地按照以下方式進行操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM