gpt4 book ai didi

mysql - Activerecord 对 sql 的转换不正确

转载 作者:行者123 更新时间:2023-11-29 03:08:59 28 4
gpt4 key购买 nike

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

最佳答案

我想,你调用类似的东西

if @votes.any?

在你看来。

方法 any? 将对表中的记录进行计数。例如,Vote.any? 会产生如下内容:

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

在您的情况下,您的 COUNT(*) AS votes_count 将替换为 COUNT(*) AS count_all,但别名 votes_count 将是留在订单条款中。

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

关于mysql - Activerecord 对 sql 的转换不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084383/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com