0

So I have this query

Vote.group(:photo_id).order('count_all desc').limit(10).count

that fetches all the votes and groups them by their photo_id and totals up the votes for those ids. I would like to add another constraint to it to only grab the ones with a vote count greater than X. I know I have to add a .where function somewhere but I'm not entirely sure where to put it or how to add in the new constraint...

4
  • 1
    Is count_all a Vote column? Commented Oct 9, 2015 at 21:59
  • 1
    I'm not rails expert but that code seems kind of odd. I think order doesn't matter when you are just counting. Also I'm not sure, but the count might always be 10 because of the limit. Please correct me if I'm wrong. Commented Oct 9, 2015 at 22:01
  • 1
    Well the count will always be 10 unless there are less than 10 votes @semperfids. But you're right using count with limit is odd. Commented Oct 9, 2015 at 22:03
  • @max Right now it's pulling 10 records max and giving me an aggregate count of the votes by photo_id, sorted by most votes descending. I want to be able to say. Only pull these if the count of the aggregate votes for the photo are greater than X. If that makes sense? Commented Oct 9, 2015 at 23:31

1 Answer 1

1

You want having (SQL keyword as well as Rails method):

http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-having

Vote.group(:photo_id).having('COUNT(*) > ?', x)…
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.