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
source share