Ruby on rails 在运行时查找ActiveRecord类的关联?
我想在运行时查找ActiveRecord类的关联 让我们假设我有以下几点:Ruby on rails 在运行时查找ActiveRecord类的关联?,ruby-on-rails,ruby,activerecord,associations,Ruby On Rails,Ruby,Activerecord,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 将返回: ["chair
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
将返回:
["chairs", "pens"]
及
将返回:
["person"]
我是不是错过了这样一个存在的方法
谢谢你的帮助 我想这门课可能就是你想要的。从文件中:
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
在运行时这么做听起来很愚蠢。你到底想达到什么目的?我认为无论你的问题是什么,都有一个简单且更常用的解决方案
如果必须的话,我会使用model.read\u inheritable\u属性(:reflections)uhh。。。想想Rake任务。需要了解关联的人。模型本身知道关联。所以我还是不明白;)
["person"]
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