祖先宝石有很多方法来导航树结构。你可以做Model.roots来显示所有的根元素等。相反怎么做?-为每个树结构返回最新的子级。
我想在我的模型中添加一个额外的列(最新的/布尔值),然后用保存后的过滤器等进行一些逻辑处理。但是这感觉有点笨拙。:/
致以最良好的问候。Asbjørn Morell
也许你可以用Class#inherited
钩子一起破解一些东西,比如在创建新子类时更新父模型的属性:
http://www.ruby-doc.org/core/classes/Class.html#M000177
老问题,仍然相关。为自己找到了一个解决方案(也有点笨拙),但我认为效果相当不错。
用这样的方法扩展Array类:
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
之后,只需像这样使用它(与之前的验证):
account = Account.find([id])
if account.has_children?
last_child = account.descendants.ancestry_last_child
end
如果您对扩展ruby/rails核心类有疑问,这将有助于
::编辑::以前的解决方案不能完全起作用。此解决方案需要updated_at
和id
列