Benjamin
Benjamin

Reputation: 2118

Display categories that have posts in Rails 4

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.

Upvotes: 1

Views: 176

Answers (1)

Ju Liu
Ju Liu

Reputation: 3999

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.

Upvotes: 1

Related Questions