will_paginate的一个隐藏的参数:total_entries

will_paginate插件很好用,但是在Rails的development模式下查看SQL日志时发现这样的现象:
使用paginate_by_sql方法来search数据时生成这样的两条SQL语句:
SELECT COUNT(*) FROM(select a.* from table_a where ... order by id asc) AS count_table

select a.* from table_a where ... order by id asc

这样的SELECT COUNT语句的性能就很有问题了。
查看will_paginate的实现-》finder.rb:
def paginate_by_sql(sql, options)
        options, page, per_page = wp_parse_options!(options)
        sanitized_query = sanitize_sql(sql)
        total_entries = options[:total_entries] || count_by_sql("SELECT COUNT(*) FROM (#{sanitized_query}) AS count_table")

        returning WillPaginate::Collection.new(page, per_page, total_entries) do |pager|
          options.update :offset => pager.offset, :limit => pager.per_page
          add_limit! sanitized_query, options
          pager.replace find_by_sql(sanitized_query)
        end
      end

原来paginate_by_sql方法有一个:total_entries参数,这样我们可以自己写优化的不需要order by的省略很多查询条件的count语句,然后将count number作为参数:total_entries传过去即可:
def get_count_of_xxx
  count_by_sql "select count(1) from table_a a where ..."
end

def get_xxx
  paginate_by_sql "select a.* from table_a where ... order by id asc", :total_entries => get_count_of_xxx
end

这样能优化不少search方法的性能

你可能感兴趣的:(设计模式,sql,Rails)