ActiveRecord查询所有没有孩子的类别?

时间:2014-03-16 20:01:06

标签: ruby-on-rails postgresql activerecord

我有一个基本架构:

class Category < ActiveRecord::Base
  has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy
  belongs_to :parent_category, class_name: 'Category'
end

我想获得所有没有任何子类别的Category对象。

如何使用ActiveRecord获取此结果?

1 个答案:

答案 0 :(得分:1)

类似的东西:

Category.where('not exists(select * 
     from subcategories sc 
     where sc.id=categories.subcategory_id)')

显然,你可以把它作为可读性的范围。