我有一个模特
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)
选择表格类别中的所有类别的范围。
请帮助我。
答案 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)') }