【问题标题】:get hierarchy of model having self refrenced parent children association rails获取具有自引用父子关联导轨的模型层次结构
【发布时间】:2016-12-27 08:20:27
【问题描述】:

我有一个模特Document,关系如下

belongs_to :parent, class_name: 'Document'
has_many :children, class_name: 'Document', foreign_key: 'parent_id'

我希望能够在文档对象上调用一个方法来检索其所有父项和子项。有没有办法通过活动记录来做到这一点

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord associations


    【解决方案1】:

    您可能想使用closure_tree gem。它对分层结构有非常方便的支持

    【讨论】:

      【解决方案2】:

      我最终在文档模型上实现了这些方法

      def get_children(level = 0, result = [])
        result.push([level, self])
        if(!self.children.empty?)
          self.children.each do |child|
            child.get_children(level+1, result)
          end
        end
        if(level == 0)
          return result
        end
      end
      
      def get_parents(result = [])
        if self.parent.present?
          result.push(self.parent)
          self.parent.get_parents(result)
        else
          return result
        end
      end
      

      【讨论】:

        猜你喜欢
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 2021-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多