导入图数据库语言,懂
- 节点(由圆圈表示),
- 边缘(由箭头表示),和
- 属性(节点/边的元数据)
图形(由维基百科提供)描述了一个有向图。
在 Rails中建模无向图的最佳方法是什么?
也就是说,所有边都是互易的图(如上图),并且无论方向如何,每条边的属性都相同(与上图相反)。
让我们假设通过 ActiveRecord 使用 sql 存储的默认 Rails 3 设置。
双多态关联将创建一个有向图,能够对上图描述的数据进行建模。
def Edge < ActiveRecord::Base
belongs_to :head, polymorphic: true
belongs_to :tail, polymorphic: true
end
class Node < ActiveRecord::Base
has_many :from, as: :head
has_many :to, as: :tail
end
class Group < ActiveRecord::Base
# a Node of Type: Group
has_many :from, as: :head
has_many :to, as: :tail
end
应该扩展这个模型来管理反向关系,还是有更好的模型可用?
应用程序的一个元素可能是图问题,但这并不意味着应用程序以问题为中心,必须对数据执行图横向,也不意味着数据集大于可用内存。