我这样做是这样的:
@disabled_options = []
Category.where('ancestry is NULL').each do |cat|
@disabled_options << cat.id if cat.has_children?
end
有没有更优雅的方法让所有父母都没有孩子?
我这样做是这样的:
@disabled_options = []
Category.where('ancestry is NULL').each do |cat|
@disabled_options << cat.id if cat.has_children?
end
有没有更优雅的方法让所有父母都没有孩子?
这个单线可以帮助你。
Category.where(id: Category.pluck(:ancestry).compact.map { |e| e.split('/') }.flatten.uniq)
Category.where("id IN (SELECT parent_id FROM categories)")
假设parent_id
是一个指向父类别的字段。
这将选择那些使用“parent_id”指向的类别,所以如果有一个孩子,孩子将设置“parent_id”,因此“parent_id”引用的类别有孩子。