Peter
Peter

Reputation: 132227

Rails scope checking for no associations

I have a Category model where a category may have some subcategories (category.categories). I want a scope that gives me all Categorys that have no subcategories.

In other words, I can write

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

but I would like to write this as a scope. How do I do this?

In case it's not clear, this is my model:

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

Upvotes: 2

Views: 381

Answers (1)

Viktor Tr&#243;n
Viktor Tr&#243;n

Reputation: 8884

the best practice is minimize db queries by implementing a counter cache. In rails this is super simple by adding an option :counter_cache => true to the belongs_to association. This assumes you create a 'categories_count' integer column in your categories db table. Given this, your scope is trivial.

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

hope this helped.

Upvotes: 4

Related Questions