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
Dario Hunt
2,245 PointsRails sorting by count
I'm using acts_as_votable with my activities model and I've been able to select only the activities that have votes on them by using a joins table. But I want to be able to select only the items that have more than a certain number of votes, for example only activity items that have 3 or more votes.
Here's my current code I use to retrieve activity items with votes:
@activities = Activity.select("activities.*, COUNT(votes.id) vote_count").joins(:votes).group("activities.id").order("created_at desc").where(:created_at => 3.months.ago..Date.today).page(params[:page]).per_page(72)
Does anyone know how I can accomplish this? Thanks in advance.
2 Answers
Nick Fuller
9,027 PointsHi Darlo,
Try something like . . .
@activites = Activity.joins(:votes)
.group("activites.id")
.having("count(votes.id) > ?", params[:vote_count])
.order("created_at desc")
.where(created_at: 3.months.ago..Time.zone.now.to_date)
.page(params[:page])
.per_page(72)
Notice I subbed in Time.zone.now.to_date and the reason is Date.today will use the server's time zone (which often is GMT) where as Time.zone.now.to_date will use the application's timezone. If your application is operating on PST.. then running this query at 4pm-5pm will actually give you results for the following day. But then again, you're going back 3 months anyway, so one day may not matter to you.
ayezee33
16,096 PointsCan one of you describe where you would place this code? Does this go in the view?
Dario Hunt
2,245 PointsDario Hunt
2,245 PointsNick Fuller This is perfect, does exactly what I was looking for and I didn't know about the time zone thing so thank you very much!