如何在Rails中使用自引用获取作用域



我有一个模型

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)选择表类别中的所有类别作为作用域。

请帮帮我。

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)') }

最新更新