Select nodes without childrens #120

Open
link82 opened this Issue Mar 1, 2013 · 4 comments

Projects

None yet

4 participants

@link82
link82 commented Mar 1, 2013

Hello, I'm trying to figure out how to tell Ancestry to retrieve all the nodes that does not have any children (last level in my tree, all the leaves)

Thanks in advance,
Davide

;)

@StefanH
Collaborator
StefanH commented Mar 1, 2013

Hi Davide,

That is difficult, since it is not a local property of a node whether it's a leaf or not. You could use a subquery in the where clause that excludes results for which there are records that match the child ancestry of the result, but that could get ugly. Alternatively you could cache the 'leaf-status' on the node. This could be a boolean, default true, that becomes false if you add a new node under a node.

@link82
link82 commented Mar 1, 2013

I think I should try the 2nd approach but I'm not sure how to do it (I'm a newbie in rails)

I'm trying something like this in my renewal.rb

has_many :childrens, :class_name => 'Renewal', :foreign_key => :ancestry
belongs_to :my_parent,:class_name => 'Renewal', :foreign_key => :ancestry,  :counter_cache => :true
def leaf?
  self.childrens.size == 0
end

but it explodes when it should update the counter with a this error

SQLite3::SQLException: no such column: true: UPDATE "renewals" SET "true" = COALESCE("true", 0) - 1 WHERE "renewals"."id" = 12

Do you mean something like this?

@antstorm
Contributor

Here's a PR that adds support for leaves scope — #238

@kbrock
Collaborator
kbrock commented Dec 14, 2016

see also #50

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment