will_paginate的一个隐藏的参数:total_entries

will_paginate插件很好用,但是在Rails的development模式下查看SQL日志时发现这样的现象:
使用paginate_by_sql方法来search数据时生成这样的两条SQL语句:
[code]
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
[/code]
这样的SELECT COUNT语句的性能就很有问题了。
查看will_paginate的实现-》finder.rb:
[code]
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
[/code]
原来paginate_by_sql方法有一个:total_entries参数,这样我们可以自己写优化的不需要order by的省略很多查询条件的count语句,然后将count number作为参数:total_entries传过去即可:
[code]
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
[/code]
这样能优化不少search方法的性能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值