jasonmklug
jasonmklug

Reputation: 1634

Rails: Return array of all Categories that contain at least one Post?

Given:

class Categories < ActiveRecord::Base
  has_many :posts
end

and

class Posts < ActiveRecord:Base
  attr_accessible :category_id

  belongs_to :category
end

How can I get an array of all Categories that have at least one associated post?

Upvotes: 0

Views: 249

Answers (1)

prasvin
prasvin

Reputation: 3019

The better (in terms of performance) solution is to have a count column in the categories table, and :counter_cache => true on the belongs_to association declaration (which you have already looked into).

More info here: http://guides.rubyonrails.org/association_basics.html#belongs_to-counter_cache

If your tables are relatively small, you can query : Category.joins(:posts).group(:category_id).having('count(category_id) >= ?', 1)

Upvotes: 2

Related Questions