Ancestry - how to get all parent without children?

你说的曾经没有我的故事 提交于 2019-12-22 13:53:01

问题


I am doing it this way:

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

Is there any more elegant way to get all parent without children?


回答1:


Category.where("id IN (SELECT parent_id FROM categories)")

Assuming parent_id is a field pointing to the parent category.

This will select those categories that are pointed to using "parent_id", so if there's a child, the child will have "parent_id" set, therefore the category referenced to by "parent_id" has children.




回答2:


This one-liner may help you.

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


来源:https://stackoverflow.com/questions/11366663/ancestry-how-to-get-all-parent-without-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!