如何在Rails中获取自引用范围?

时间:2015-11-20 08:35:49

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4

我有一个模特

class Category < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Category'
  has_many :children, :class_name => 'Category', :foreign_key => 'parent_id'
end

我想使用category.children == nil(category.children.count == 0)选择表格类别中的所有类别的范围。

请帮助我。

1 个答案:

答案 0 :(得分:3)

scope :no_children, -> { includes(:children).where(children: { id: nil }) }

scope :without_children, { where('not exists (select null from children where children.parent_id = category.id)') }