2

我这样做是这样的:

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

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

4

2 回答 2

2

这个单线可以帮助你。

Category.where(id: Category.pluck(:ancestry).compact.map { |e| e.split('/') }.flatten.uniq)
于 2016-11-09T13:10:06.890 回答
1
Category.where("id IN (SELECT parent_id FROM categories)")

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

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

于 2012-07-06T18:32:39.043 回答