代码之家  ›  专栏  ›  技术社区  ›  JP Richardson

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

  •  8
  • JP Richardson  · 技术社区  · 17 年前

    让我们假设我有以下几点:

    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.has_many_assocations 
    

    将返回:

    ["chairs", "pens"] 
    

    和

    Pen.belongs_to_associations
    

    将返回:

    ["person"]
    

    我是不是错过了这样一个存在的方法??

    2 回复  |  直到 17 年前
        1
  •  26
  •   Angela    17 年前

    我认为 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
    
        2
  •  0
  •   August Lilleaas    17 年前

    TheModel.read_inheritable_attribute(:reflections) .

    推荐文章