模型上的Rails .page调用也会调用计数 [英] Rails .page call on model also calls count

查看:81
本文介绍了模型上的Rails .page调用也会调用计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试做一个简单的Model.all.page(1)
但是,每当调用.page时,它都会创建一个SQL COUNT调用. (我的实际代码比上面的代码更复杂,但是为了易于阅读而简化了.)有没有一种方法可以防止.page调用SQL计数?我正在处理数百万种产品,此调用使页面刷新需要额外的2秒钟才能加载.我已经有自己的即时计数,因此我不需要此.page计数.

Trying to do a simple Model.all.page(1)
But whenever .page is called, it creates a SQL COUNT call. (My actual code is more complex than above, but simplified for ease of reading.) Is there a way to prevent .page from calling a SQL count? I'm dealing with millions of products and this calls is making the page refresh take an extra 2 seconds to load. I already have my own custom count which is instant so I don't need this .page count.

Def不使用.all.不好的例子对不起.

Def not using .all. Bad example sorry.

这里有一个非常简单的示例,简而言之就是我的代码: Product.limit(1).page(1)

用我的真实代码,SQL产生:(1495.3ms) SELECT COUNT(*) FROM 'products' LEFT OUTER JOIN...

Heres a really simple example that is basically my code in a nutshell: Product.limit(1).page(1)

With my real code SQL produces: (1495.3ms) SELECT COUNT(*) FROM 'products' LEFT OUTER JOIN...

我在product表上加入了不需要计数的联接,因此,事实是我有自己想使用的计数方法,不需要.page即可产生自己的计数.

I have joins on the products table that I don't need to be counted, hence the fact I have my own count methods I want to use and don't need .page to produce it's own count.

推荐答案

调用Model.all.page(1)时,您将获得数组而不是ActiveRecord关系.

When you call Model.all.page(1) you are getting back an array instead of an ActiveRecord relation.

尝试仅致电Model.page(1),您应该得到想要的...如果想要的是:

Try just calling Model.page(1) and you should get what you want... If what you want is:

Model.page(1)

# results in SELECT "models".* FROM "models" LIMIT 30 OFFSET 0

修改: 因此,问题最终出现在will_paginate gem中,因为它正在调用查询的count来知道条目的总数,以便可以获取准确的页面数.但是will_paginate确实为paginate方法提供了一个选项,该选项使您可以传递自定义total_entries计数,如果您有一个庞大的表并且不关心获取与之匹配的每条记录的准确页数,则此选项很有用查询.

So the issue ended up being in the will_paginate gem as it was calling count on the query to know the total number of entries so it can get an accurate number of pages. However will_paginate does provide an option to the paginate method which allows you to pass in a custom total_entries count which is useful if you have a massive table and don't care to get the precise number of pages for every record that matches the query.

您可以像这样传递选项:

You can pass in the option like so:

Model.paginate(:page => params[:page], :per_page => 30, :total_entries => 100)

这篇关于模型上的Rails .page调用也会调用计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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