我有一个模型
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)') }