I am using Ruby on Rails 3.2.9 and the WillPaginate 3.0 ruby gem. As pointed out by many resources on Internet (keep reading for more information), it seems that something doesn't work as expected on counting objects with the WillPaginate gem when "complex" associations / scoping methods are involved, since this issue makes it to generate a wrong amount of page links in related views. In my case the problem is similar to this and this.
In my model class Article
I have:
has_many :category_associations
has_many :categories, :through => :category_associations
In the related controller ArticleControllers
I have :
@article
.categories
.scope_method(...)
.order_method
.search_method(...)
.paginate(:page => 1, :per_page => 10)
Proposed solutions on the Internet are:
Article 1: The solution is to add a count
condition this way:
@article =
<...> # Same as above.
.paginate(:per_page => 4, :page => params[page], :count => {:group => 'articles.id'})
Article 2: The solution is to manually count objects and set the total_entries
option this way:
# Note: The below code is performance less since a further SQL query is executed.
total_entries = ... # Pre-count the amount of objects, as needed (note: in this code line it is executed a SQL query to the database).
@article =
<...> # Same as above.
.paginate(:per_page => 4, :page => params[page], :total_entries => total_entries)
I tried and made to work all the above solutions, but I would like to understand what could be the "internal" issue related to the WillPaginate gem (so that I can adjust it) and how I should proceed to properly solve my problem (for example, what is the "best" solution? are there other solutions than the above ones?).
For instance, I would like to avoid to use "hacked" solutions like those presented above but to use the paginate
method the "common" way: @articles.<...>.paginate(:per_page => 4, :page => params[page])
.