【问题标题】:Ancestry - how to get all parent without children?祖先 - 如何让所有父母都没有孩子?
【发布时间】:2012-07-06 17:06:21
【问题描述】:

我是这样做的:

@disabled_options = []
Category.where('ancestry is NULL').each do |cat|
  @disabled_options << cat.id if cat.has_children?
end

有没有更优雅的方法让所有的父母都没有孩子?

【问题讨论】:

  • 您要查找所有“父母”(所有有孩子的类别)还是要查找所有“根”(所有没有父母的类别)?
  • 所有有孩子的类别

标签: ruby-on-rails ancestry


【解决方案1】:

这条单线可能会对您有所帮助。

Category.where(id: Category.pluck(:ancestry).compact.map { |e| e.split('/') }.flatten.uniq)

【讨论】:

    【解决方案2】:
    Category.where("id IN (SELECT parent_id FROM categories)")
    

    假设parent_id是一个指向父类的字段。

    这将选择那些使用“parent_id”指向的类别,所以如果有一个孩子,孩子将设置“parent_id”,因此“parent_id”引用的类别有孩子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 2011-07-23
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多