Family tree: return only the last child to the threads

ancestry gem has many ways to navigate the tree structure. You can do Model.roots to show all root elements, etc. How to do the opposite? - return a new child for each tree structure.

I thought about adding an extra column to my model (last / boolean), and then I will do some logic after the save filters, etc. However, this seems a bit awkward.: /

Sincerely. Asbjorn Morell

+4
source share
2 answers

Perhaps you can crack something along with the Class#inherited hook, for example, update the attribute of the parent model when creating a new subclass:

http://www.ruby-doc.org/core/classes/Class.html#M000177

0
source

The old question is still relevant. I found a solution (a bit awkward), but I think it works quite well.

Extend the Array class as follows:

 class Array def ancestry_last_child last_child = self.map { |a| [a[:id], a[:ancestry], a[:updated_at]] }.sort_by { |id, anc, dat| [anc.split('/').length, dat] }.last self.find { |a| a[:id] == last_child[0] } end end 

After that, just use it (with the previous validation) as follows:

 account = Account.find([id]) if account.has_children? last_child = account.descendants.ancestry_last_child end 

if you have doubts about expanding the main classes of rubies / rails, this will help

:: EDIT :: previous solution did not work fully. This solution requires an updated_at and id column

0
source

All Articles