【问题标题】:Get attributes of children in a recursive tree structure unless it's a leaf node获取递归树结构中子节点的属性,除非它是叶节点
【发布时间】:2014-12-15 03:24:29
【问题描述】:

我有一个递归树结构来处理我的类别。每个叶类别可以有零个或多个交易。类别由

定义
class Category < ActiveRecord::Base
  has_many :sub_categories, class_name: "Category", foreign_key: "parent_category_id"
  belongs_to :parent_category, class_name: "Category"

  has_many :deal_categories
  has_many :deals, through: :deal_categories

  def leaf?
    !has_sub_categories?
  end

  def has_sub_categories?
    !sub_categories.empty?
  end
end

DealsDealCategories 如下所示:

class Deal < ActiveRecord::Base
  has_many :deal_categories
  has_many :categories, through: :deal_categories
end

class DealCategory < ActiveRecord::Base
  belongs_to :deal
  belongs_to :category
end

还有一些验证可以确保只有Deals可以作为叶类别存在。因此,如果我在叶节点上调用category.deals,我会得到一些交易,如果我在根节点上调用它,我会得到一个空结果。都很好。

但是现在我希望category.deals 返回它的子节点的交易,如果它不是根节点的话。我的方法是在我的Category 类中重写以下方法,如下所示:

  alias_method :original_deals, :deals
  def deals
    if leaf?
      self.original_deals
    else
      self.sub_categories.deals
    end
  end

但这不起作用,因为我不能直接在 sub_categories 上调用 deals,错误是

undefined method `deals' for #<Category::ActiveRecord_Associations_CollectionProxy:0x00000009243d40>

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails-4 tree overriding getter recursive-datastructures


    【解决方案1】:

    您不能在 sub_categories 上调用交易,因为它不是一个类别……它是一个类别的集合。相反,你可以做类似

    sub_categories.reduce([]) { |union, sub_category| union + sub_category.deals }
    

    使用 reduce 创建一个 memo 对象(由 union 变量表示)并且块的评估成为新的 memo 对象。我从一个空数组开始,并在您的 sub_categories 集合中的每个 sub_category 上添加调用交易的结果。

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2021-08-15
      • 1970-01-01
      • 2021-02-13
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多