How can I get SQL statement created by ActiveRecord#find without actually executing it?

前端 未结 5 1698
灰色年华
灰色年华 2020-12-30 21:46

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 pag

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-30 22:33

    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
    

提交回复
热议问题