开发者

Ancestry gem: return only last child in threads

开发者 https://www.devze.com 2023-03-16 12:57 出处:网络
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 structur

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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消