1

Trying to display a list of categories that have posts. Sounds simple but i'm a little stuck. Similar to this

ActiveRecord find all parents that have associated children

class Category < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :category
end

Can you please help. I tried named scope but breaks the app.

Community
  • 1
  • 1
Benjamin
  • 2,108
  • 2
  • 26
  • 46

1 Answers1

1

You could either use a scope like this

scope :with_posts, -> { includes(:posts).where("posts.id IS NOT NULL") }

or using counter_cache

class Category < ActiveRecord::Base
  has_many :posts
  scope :with_posts, -> { where("posts_count > ?", 0) }
end

class Post < ActiveRecord::Base
  belongs_to :category, counter_cache: true
end

Note that you have to add a posts_count integer field to the categories table for this to work. It is also advisable to save all your categories the first time to populate this field.

Ju Liu
  • 3,939
  • 13
  • 18
  • Works when i use it on the controller def show @categories = Category.where('posts_count > ?', 0) end – Benjamin Jun 27 '13 at 16:10