问题
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.
Edit: Def not using .all. Bad example sorry.
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...
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.
回答1:
When you call Model.all.page(1)
you are getting back an array instead of an ActiveRecord relation.
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
Edit:
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)
回答2:
You are concerned about doing a COUNT query, yet you are selecting ALL records from your database by doing Model.all? Are you joking right now? Also you need to provide code in order to get help. We cant read your mind, we cant make up what code you might have. Especially when you say "my actual code is more complex than above". Don't try to simplify issues or hide code that you THINK is irrelevant.
What does your code look like? What does your log look like, specifically query time and total page time (rendering and ActiveRecord split out). You need to give more information.
来源:https://stackoverflow.com/questions/21713016/rails-page-call-on-model-also-calls-count