代码之家  ›  专栏  ›  技术社区  ›  fl00r

模型的关系

  •  2
  • fl00r  · 技术社区  · 16 年前

    如何获取模型的所有关系。艾丽,我有 User 型号:

    class User < AR::Base
      has_many :messages, :foreign_key => 'author'
      has_many :posts
      belongs_to :role
    end
    

    用户 模特有吗?以及外键(如果有)。

    1 回复  |  直到 16 年前
        1
  •  7
  •   Alex Wayne    16 年前
    User.reflect_on_all_associations.each do |assoc|
      puts "#{assoc.macro} #{assoc.name}"
    end
    

    输出:

    has_many messages
    has_many posts
    belongs_to role
    

    这个 reflect_on_all_associations MacroReflection 物体。它们还支持其他方法,用于查询每个关联的选项散列和其他有用的内容。