1

I have a basic Schema:

class Category < ActiveRecord::Base
  has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id', dependent: :destroy
  belongs_to :parent_category, class_name: 'Category'
end

I want to get all Category objects that DO NOT have any subcategories.

How can I use ActiveRecord to get this result?

Dan Tapia
  • 11
  • 1
  • 1
    http://stackoverflow.com/questions/18082096/rails-4-scope-to-find-parents-with-no-children Similar question? – Pierre Mar 16 '14 at 20:06
  • @Pierre: Using the query in the linked question results in: `ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "subcategories"` – Dan Tapia Mar 16 '14 at 20:10
  • Post your code in the question. – Pierre Mar 16 '14 at 20:11
  • The following Answer http://stackoverflow.com/a/18082147/976775 was updated to match the self-referential cases. In your case, it would be something like `includes(:subcategories).where(subcategories_categories: { id: nil })` – MrYoshiji May 22 '14 at 18:35

1 Answers1

1

something like:

Category.where('not exists(select * 
     from subcategories sc 
     where sc.id=categories.subcategory_id)')

Obviously you can make it a scope for readability.

maniek
  • 7,087
  • 2
  • 20
  • 43