2

我正在使用 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`
4

1 回答 1

1

我猜,你叫类似

if @votes.any?

在你看来。

方法any?将计算表中的记录。例如,Vote.any?将产生如下内容:

SELECT COUNT(*) AS count_all FROM `votes`;

在您的情况下,您COUNT(*) AS votes_count将被替换为COUNT(*) AS count_all,但别名votes_count将保留在 order 子句中。

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
于 2012-07-17T10:02:01.260 回答