Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Sage Elliott
Sage Elliott
30,003 Points

Rails Sorting by .post.count

Hello! I've been developing a blog in rails and I'm having some issues with a small feature. I would really like to be able to sort the tags on the page by the number of posts they have attached to them. I used a tagging system like the one found at this jumpstart tutorial. Maybe its not the way I should have gone. I'm not sure how I would write the sequel in the controller to order it since I would assume I have to join tables?

The relationship is such

#tag.rb
has_many :taggings
has_many :posts, through: :taggings

#post.rb
has_many :taggings
has_many :tags, through: :taggings

#tagging.rb
belongs_to :tag
belongs_to :post

I can call in the count easily enough once I have a specify tag selected.

tag = Tag.first
tag.posts.count

#outputs post count on tag

Any help would be much appreciated!

Sage Elliott
Sage Elliott
30,003 Points

Or let me know if you think there is a better way for setting up a tagging relationship

1 Answer

Sage Elliott
Sage Elliott
30,003 Points

I got it! I had originally tried using counter cache due to some great stackoverflow posts, but the problem was my logic. I was trying to count the posts from the tag, and not the taggings face palm