我怎样才能获得通过的ActiveRecord#查找创建的SQL语句,而无需实际执行呢? [英] How can I get SQL statement created by ActiveRecord#find without actually executing it?

查看:160
本文介绍了我怎样才能获得通过的ActiveRecord#查找创建的SQL语句,而无需实际执行呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 will_paginate 有一些复杂的查询,这是无法正确计算(以显示页面链接适当数量)总记录数 - 因为即分组由多个列。

I am using will_paginate with some complicated queries and it is unable to correctly calculate number of total records (in order to display proper number of page links) - namely because of grouping by multiple columns.

所以,我打算让SELECT查询,它会被用于检索的所有记录,没有实际执行它,并用 SELECT COUNT(*)FROM ... 手动,为了得到的记录数

So, I am intending to get the SELECT query which would be used to retrieve ALL records, without actually executing it, and wrap it with SELECT COUNT(*) FROM ... manually, in order to get the number of records.

任何想法怎么办呢?

编辑:我使用Rails 2.3.x

I am using Rails 2.3.x

推荐答案

这似乎thatm在Rails的2.X,一个私有方法称为<一个href="http://apidock.com/rails/ActiveRecord/Base/construct_finder_sql/class"><$c$c>ActiveRecord::Base#construct_finder_sql也可以使用,我需要更多的测试,看看它是否会为我工作:

It seems thatm in Rails 2.x, a private method called ActiveRecord::Base#construct_finder_sql could be used, I need to test it more and see whether it will work for me:

ActionType.find(:all, :select => 'hosted, top_action_type, count(*) as count', :group => 'hosted, top_action_type').count
#=> 6
sql = ActionType.send :construct_finder_sql, :select => 'hosted, top_action_type, count(*) as count', :group => 'hosted, top_action_type'
#=> "SELECT hosted, top_action_type, count(*) as count FROM "action_types"  GROUP BY hosted, top_action_type"
ActionType.count_by_sql "SELECT COUNT(*) FROM (#{sql}) a"
#=> 6

这篇关于我怎样才能获得通过的ActiveRecord#查找创建的SQL语句,而无需实际执行呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆