【发布时间】:2014-06-04 04:18:49
【问题描述】:
如何使用 will_paginate 对预先排序的记录集合进行分页?
环境:Ruby 2.0.0、Rails 4.0.3、Windows 8.1、PostreSQL、Datatable 1.12.2、Will_Paginate 3.0.5
使用 Railscast 340 代码,我正在尝试完成我的数据表实现。我有几列需要独立排序,因为它们存在于关联中并且不能直接访问。为了简单起见,我只在一个方向上显示了一列。
排序在标准情况和“product_location”情况下都有效。记录集合中提供了正确的记录,并且在这两种情况下它们的顺序都正确。
在“product_location”案例中,当我尝试对结果进行分页时,will_paginate 似乎从表中检索记录,而不是使用我的记录集合。我最终以错误的顺序得到错误的记录。这个动作对我来说没有意义,所以我一定错过了一些东西。
标准排序在所有列上双向工作。
我的代码如下,后面是Railscast 340的原始代码:
def products
@products ||= fetch_products
end
def fetch_products
case sort_column
when "product_location"
products = Product.all
products.sort_by!{|product| product.readable_loc} # product_location sort
else
products = Product.order("#{sort_column} #{sort_direction}") # standard sort
end
# products is correctly sorted in both cases at this point
products = products.page(page).per_page(per_page)
# At this point, products is correctly sorted in the standard case but not in the "product_location" case
# In "product_location" case, pagination seems to be accessing the table directly again, not using the record collection?
if params[:sSearch].present?
products = products.where("stock_number like :search", search: "%#{params[:sSearch]}%")
end
products
end
原代码为:
def products
@products ||= fetch_products
end
def fetch_products
products = Product.order("#{sort_column} #{sort_direction}")
products = products.page(page).per_page(per_page)
if params[:sSearch].present?
products = products.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
end
products
end
【问题讨论】:
标签: sql ruby-on-rails sorting pagination will-paginate