samedi 11 juin 2016

How to count unvoted Options powered by "thumbs_up" gem

Poll has_many Questions, Question has_many Options, Option acts_as_voter

I tried to count unvoted options

this work

[22] pry(main)> unvoted = Option.tally.where('question_id = ?', 3).having('COUNT(votes.id) = 0')
  Option Load (0.3ms)  SELECT options.*, COUNT(votes.id) AS  vote_count FROM "options" LEFT OUTER JOIN votes ON options.id = votes.voteable_id WHERE (question_id = 3) GROUP BY options.id, options.content, options.question_id, options.created_at, options.updated_at HAVING COUNT(votes.id) = 0 ORDER BY vote_count DESC

but when I do this I get an error

[23] pry(main)> unvoted_count = Option.tally.where('question_id = ?', 3).having('COUNT(votes.id) = 0').count
   (0.5ms)  SELECT COUNT(options.*, COUNT(votes.id) AS vote_count) AS count_options_all_count_votes_id_as_vote_count, options.id, options.content, options.question_id, options.created_at, options.updated_at AS options_id_options_content_options_question_id_options_created_at_options_updated_at FROM "options" LEFT OUTER JOIN votes ON options.id = votes.voteable_id WHERE (question_id = 3) GROUP BY options.id, options.content, options.question_id, options.created_at, options.updated_at HAVING COUNT(votes.id) = 0  ORDER BY vote_count DESC
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "*": syntax error: SELECT COUNT(options.*, COUNT(votes.id) AS vote_count) AS count_options_all_count_votes_id_as_vote_count, options.id, options.content, options.question_id, options.created_at, options.updated_at AS options_id_options_content_options_question_id_options_created_at_options_updated_at FROM "options" LEFT OUTER JOIN votes ON options.id = votes.voteable_id WHERE (question_id = 3) GROUP BY options.id, options.content, options.question_id, options.created_at, options.updated_at HAVING COUNT(votes.id) = 0  ORDER BY vote_count DESC
from /usr/lib/ruby/gems/2.3.0/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize'

also I tried this, which I dont know why ignore conditions, why?

[14] pry(main)> Option.count(:conditions => "question_id = 3 AND HAVING COUNT(votes.id) = 1")
   (0.3ms)  SELECT COUNT(*) FROM "options"
3

this also ignore conditions

Option.count(:conditions => "question_id = 3 AND COUNT(votes.id) = 1")

Aucun commentaire:

Enregistrer un commentaire