Ruby 映射未知 parent-child 关系(组合而非继承)& 获取 parent/child 名称或 object 已知 object?

Ruby map unknown parent-child relationship (composition not inheritance) & get parent/child name or object given one known object?

假设我想映射一个未知的 parent-child 关系,其中我有一个已知的 @object_instance,它本身可能是 parent 或 child。然后我想看看这个 @object_instance 是否有任何 parents 或 children,然后适当地列出 ID。例如,在 pseudo-code:

def map_relationships
  if self.has_children
    puts "This object has children named #{self.child.class_name} with ID(s) #{self.children.map(&:id)}"
  end
  if self.has_parent
    puts "This object has a parent named #{self.parent.class_name} with ID(s) #{self.parent.id}"
  end
end

假设 Company has_many Sites 和一个 Site has many Offices,并且 @object_instance 是一个站点,那么上述方法的结果将是:

@object_instance.map_relationships
> "This object has children named Desks with ID(s) [5,6,7]"
> "This object has a parent named Company with ID(s) 4"

这样的事情可能吗?我浏览了 public_methods 中的 Class 和它的一个实例,但没有看到明显的东西。

谢谢!

我找到了一个方法,基本上你可以使用reflect_on_all_associations构造上面的方法,它的工作原理是这样的:

# get parent
@object_instance.class.reflect_on_all_associations(:belongs_to)
# returns an array, like below
# [:company]

# get children
@object_instance.class.reflect_on_all_associations(:has_many)
# returns an array, like below
# [:desks]

如果有其他巧妙的方法可以做到这一点,欢迎提供其他答案