4

The ancestry gem has a lot of methods to navigate the tree structure. You can do Model.roots to show all root elements etc. How do opposite? - return newest child for each tree structure.

I thought about adding an extra column to my model (latest/boolean) and then do some logic with after save filters etc. However this feels a bit clumsy. :/

Best regards. Asbjørn Morell

atmorell
  • 3,052
  • 6
  • 30
  • 44

2 Answers2

0

Old question, still relevant. Found myself a solution (bit clumsy as well) but I think it works fairly well.

Extend the Array class with a method like this:

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 preceding validation) like this:

account = Account.find([id])

if account.has_children?
  last_child = account.descendants.ancestry_last_child
end

if you have doubts about extending ruby/rails core classes this will help

::EDIT:: previous solution didn't work in full. This solution requires an updated_at and id column

Community
  • 1
  • 1
tostasqb
  • 717
  • 1
  • 12
  • 28
0

Maybe you can hack something together with the Class#inherited hook, like updating an attribute of the parent model on creation of the new subclass:

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

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158