我正在使用 rails 3.2.3、rspec 2.9.0、mysql5.1
原来的要求是
def index
@votes = current_contest.votes.select('COUNT(*) AS votes_count, submission_id').group('submission_id').order('votes_count DESC')
end
在开发环境中一切正常,但在我的测试中我得到了错误(ActiveRecord 添加额外的别名并重写我的)
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
我可以在这样的简单查询中捕获此错误
def index
@votes = Vote.select('COUNT(*) AS votes_count, submission_id')
end
日志输出是
SELECT COUNT(*) FROM `votes`
但!!!如果我做
def index
@votes = Vote.select('COUNT(*) AS votes_count, submission_id')
@votes.inspect # or something else calling @votes
end
我在控制台日志中得到了正确的 sql 查询
SELECT COUNT(*) AS votes_count, submission_id FROM `votes`