I’m seeing exceptions from the will_paginate gem when trying to process search results if the results happen to be nil.
Here’s the code:
@posts = Post.search(query).paginate(:page => params[:page], :per_page => 8)
So it’s easy enough to add in an if statement to make sure that paginate never gets called on nil:
if !Post.search(query).nil?
@posts = Post.search(query).paginate(:page => params[:page], :per_page => 8)
end
However, imagine that my Post.search(query) returns something like 500,000 posts.
Will_paginate is smart enough to append a LIMIT to the SQL query in a lazy fashion, so that the database never has to cough up all 500,000 (only, in this case, 8 per page at a time).
My concern is that the Post.search(query).nil? does not have this LIMIT applied to it, and so it may be returning all 500,000 posts, just to determine whether the query is nil! That seems crazy.
Beyond that concern about querying for the whole 500,000 results, the other disadvantage of the way I’m doing it here is that it involves two separate Post.search requests.
Is there a more graceful way to ensure that I can avoid these paginate was called on nill errors, without hitting the database more than I need to?
You can try to use the method
.tryinstead ofif !Post.search(query).nil?Your code should look something like this:
PS.
if Post.search(query)will be enough as well.