Reputation: 139
I have 2 models:
class Section < ActiveRecord::Base
has_and_belongs_to_many :posts
end
and
class Post < ActiveRecord::Base
has_and_belongs_to_many :sections
end
I need to select all sections that has at least one associated post and order this sections by count of assotiated posts. Can anyone help me?
Upvotes: 0
Views: 276
Reputation: 5081
I had no opportunity to test this code, but it looks about right.
Section.select("sections.*, count(posts.id) AS post_count").
joins(:posts).
group("sections.id").
order("post_count DESC")
Upvotes: 2