我想在运行时找到 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
如何在运行时发现 Person“有很多”椅子和笔,反之亦然?我正在寻找一种返回字符串数组的方法(如果存在这样的方法)。即
Person.has_many_assocations
会返回:
["chairs", "pens"]
和
Pen.belongs_to_associations
会返回:
["person"]
我是否遗漏了这样一种存在的方法??
感谢您的帮助。
最佳答案
我认为 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
关于ruby-on-rails - 在运行时查找 ActiveRecord 类的关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/644718/