如何使用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
这是因为Product.all
返回实例ActiveRecord::Relation
并products.sort_by!
从数据库中获取所有记录,并使用ruby对它们进行排序。比起调用products = products.page(page).per_page(per_page)
它,它会使用new创建新的sql查询,limit
并offset
获取给定页面上的记录。
因此,如果要使用will_paginate进行分页,则不能使用.sort_by!
method进行数据排序,但是必须对记录进行排序,并使用Products.order
这些记录通过SQL对数据库中的记录进行排序。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句