Rails如何获取模型链表的叶节点

时间:2013-02-28 09:43:12

标签: ruby-on-rails-3 ruby-on-rails-3.1

我想创建一个模型的链接列表,这种结构的排序

A <- B <- C // (C is the leaf)
D <- E <- F // (F is the leaf)
G <- H // (H is the leaf)
I // (I has no children, I itself is the leaf)

我在像这样的红宝石模型中完成了它

class Node < ActiveRecord::Base
  has_one :child, class_name: "Node", foreign_key: "parent_id", dependent: :destroy
  belongs_to :parent, class_name: "Node"
end

我想获得仅仅CFHI的叶节点列表,我知道我将如何在SQL中执行此操作,我怎么在铁轨上做?我在轨道3.1上。

1 个答案:

答案 0 :(得分:0)

一种纯红宝石溶液,性能不高:

Node.all.select {| N | n.child.blank?}

基本上在rails中编写SQL解决方案:

Node.joins("LEFT JOIN nodes AS children ON nodes.id = children.parent_id").where("children.id IS NULL")