0

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

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

我只想获取叶节点列表,即,C和,我知道如何在 SQL 中执行此操作,如何在 rails 中执行此操作?我在rails 3.1上。FHI

4

1 回答 1

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")
于 2013-02-28T14:49:53.847 回答