2

我有一个Category模型,其中 acategory可能有一些子类别(category.categories)。我想要一个范围,它可以给我所有Category没有 sub 的 s categories

换句话说,我可以写

without_subcategories = Category.select{|category| category.categories.none?}

但我想把它写成scope. 我该怎么做呢?

如果不清楚,这是我的模型:

class Category < ActiveRecord::Base
  belongs_to :parent, class_name: 'Category'
  has_many :categories, foreign_key: :parent_id, class_name: 'Category'
  scope :without_subcategories, lambda { WHAT GOES IN HERE? }
end
4

1 回答 1

4

最佳实践是通过实现计数器缓存来最小化数据库查询。在 rails 中,通过向:counter_cache => truebelongs_to 关联添加一个选项非常简单。这假设您在类别数据库表中创建一个'categories_count'整数列。鉴于此,您的范围是微不足道的。

class Category < ActiveRecord::Base
  belongs_to :parent, class_name: 'Category', :counter_cache => true
  has_many :categories, foreign_key: :parent_id, class_name: 'Category'
  scope :without_subcategories, where(categories_count: 0)
end

希望这有帮助。

于 2012-06-03T01:48:02.663 回答