Mla*_*vić 25 activerecord ruby-on-rails count
我正在使用will_paginate
一些复杂的查询,它无法正确计算总记录数(为了显示正确数量的页面链接) - 即由于多列分组.
因此,我打算获取SELECT查询,该查询将用于检索所有记录,而不实际执行它,并SELECT COUNT(*) FROM ...
手动包装,以获取记录数.
有什么想法怎么做?
编辑:我正在使用Rails 2.3.x.
yfe*_*lum 42
对于Rails 3:
在Rails 3文档中查看ActiveRecord :: Relation 文档.
# get the relation
rel = User.complex_scope.chained_complex_scope
# get the SQL
# this does not execute the query
sql = rel.to_sql
# find out how many records
# this executes the query behind the scenes
count = rel.size
Run Code Online (Sandbox Code Playgroud)
Mla*_*vić 10
看起来在Rails 2.x中,ActiveRecord::Base#construct_finder_sql
可以使用一个名为的私有方法,我需要对它进行更多测试,看看它是否对我有用:
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
Run Code Online (Sandbox Code Playgroud)