WillPaginate:了解关联和范围集合的分页计数

时间:2013-05-30 14:34:28

标签: ruby-on-rails ruby pagination associations will-paginate

我正在使用Ruby on Rails 3.2.9和WillPaginate 3.0 ruby​​ gem。正如互联网上的许多资源所指出的那样(继续阅读以获取更多信息),当涉及“复杂”关联/范围方法时,使用WillPaginate gem对计算对象的某些内容似乎无法正常工作,因为此问题使其在相关视图中生成错误数量的页面链接。就我而言,问题类似于thisthis

在我的模型课Article中,我有:

has_many :category_associations
has_many :categories, :through => :category_associations

在相关控制器ArticleControllers中,我有:

@article
  .categories
  .scope_method(...)
  .order_method
  .search_method(...)
  .paginate(:page => 1, :per_page => 10)

互联网上提出的解决方案是:

Article 1:解决方案是以这种方式添加count条件:

@article =
  <...> # Same as above.
  .paginate(:per_page => 4, :page => params[page], :count => {:group => 'articles.id'})

Article 2:解决方案是手动计算对象并以这种方式设置total_entries选项:

# 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)

我尝试并努力工作以上所有解决方案,但我想了解可能是与WillPaginate gem相关的“内部”问题(以便我可以调整它)以及我应该如何进行正确解决我的问题(例如,什么是“最佳”解决方案?还有其他解决方案吗?)。

例如,我想避免使用上面提到的“黑客”解决方案,而是使用paginate方法“常见”方式:@articles.<...>.paginate(:per_page => 4, :page => params[page])

0 个答案:

没有答案