在运行时查找ActiveRecord类的关联?

JP *_*son 8 ruby activerecord ruby-on-rails associations

我想在运行时找到ActiveRecord类的关联...

我们假设我有以下内容:

class Person < ActiveRecord::Base
  has_many :chairs
  has_many :pens
end

class Chair < ActiveRecord::Base
  belongs_to :person
end

class Pen < ActiveRecord::Base
  belongs_to :person
end
Run Code Online (Sandbox Code Playgroud)

如何在运行时发现Person"有很多"椅子和笔,反之亦然?我正在寻找一个返回字符串数组的方法(如果存在这样的方法).即

Person.has_many_assocations 
Run Code Online (Sandbox Code Playgroud)

会回来:

["chairs", "pens"] 
Run Code Online (Sandbox Code Playgroud)

Pen.belongs_to_associations
Run Code Online (Sandbox Code Playgroud)

会回来:

["person"]
Run Code Online (Sandbox Code Playgroud)

我错过了这样存在的方法吗?

谢谢你的帮助.

Ang*_*ela 26

我认为ActiveRecord :: Reflection类可能就是你想要的.从文档:

  Account.reflect_on_all_associations             # returns an array of all associations
  Account.reflect_on_all_associations(:has_many)  # returns an array of all has_many associations
Run Code Online (Sandbox Code Playgroud)