【问题标题】:Ancestry gem: return only last child in threads祖先宝石:仅返回线程中的最后一个孩子
【发布时间】:2023-04-05 19:57:02
【问题描述】:

ancestry gem 有很多方法来导航树结构。你可以做 Model.roots 来显示所有的根元素等。如何做相反的? - 返回每个树结构的最新子节点。

我考虑在我的模型中添加一个额外的列(最新/布尔值),然后使用保存后过滤器等执行一些逻辑。但这感觉有点笨拙。 :/

最好的问候。 阿斯比约恩·莫雷尔

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3


    【解决方案1】:

    也许你可以用 Class#inherited 钩子一起破解一些东西,比如在创建新子类时更新父模型的属性:

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

    【讨论】:

      【解决方案2】:

      老问题,仍然相关。 为自己找到了一个解决方案(也有点笨拙),但我认为它运作良好。

      用这样的方法扩展 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 核心类有疑问,this 会有所帮助

      ::编辑:: 以前的解决方案没有完全起作用。此解决方案需要 updated_atid

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多