I’m using rails 3.2.3, rspec 2.9.0, mysql5.1
The original request is
def index
@votes = current_contest.votes.select('COUNT(*) AS votes_count, submission_id').group('submission_id').order('votes_count DESC')
end
In development env all works fine, but in my test I got error(ActiveRecord add additional aliases and rewrite mine)
ActionView::Template::Error:
Mysql2::Error: Unknown column 'votes_count' in 'order clause': SELECT COUNT(*) AS count_all, submission_id AS submission_id FROM `votes` INNER JOIN `invitations` ON `votes`.`invitation_id` = `invitations`.`id` WHERE `invitations`.`contest_id` = 1 AND (`invitations`.`status` = 'used') GROUP BY submission_id ORDER BY votes_count DESC
I can catch this error on a simple query like this
def index
@votes = Vote.select('COUNT(*) AS votes_count, submission_id')
end
log output is
SELECT COUNT(*) FROM `votes`
BUT!!! If I do
def index
@votes = Vote.select('COUNT(*) AS votes_count, submission_id')
@votes.inspect # or something else calling @votes
end
I got the correct sql query in console log
SELECT COUNT(*) AS votes_count, submission_id FROM `votes`
I guess, you call something like
in your view.
Method
any?will count records in the table.For instance,
Vote.any?will produce something like:In your case your
COUNT(*) AS votes_countwill be replaced withCOUNT(*) AS count_all, but aliasvotes_countwill be left in the order clause.