【问题标题】:How do I paginate a pre-sorted record collection using will_paginate?如何使用 will_paginate 对预先排序的记录集合进行分页?
【发布时间】: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


    【解决方案1】:

    这是因为Product.all 返回ActiveRecord::Relation 的实例,而products.sort_by! 从数据库中获取所有记录,并使用 ruby​​ 对它们进行排序。如果您调用products = products.page(page).per_page(per_page),它会使用新的limitoffset 创建新的sql 查询来获取给定页面上的记录。

    所以如果要使用 will_paginate 进行分页,则不能使用.sort_by! 方法进行数据排序,而必须使用Products.order 对记录进行排序,这将通过SQL 对数据库中的记录进行排序。

    【讨论】:

    • 嗨!这是问题 24001705 中讨论的问题。我更愿意通过 Products.order 来解决。但是,这些列不是原生的,而是通过多态关联构建的。你能帮我回答这个问题吗?
    • 好的,我会尝试添加该问题的答案。
    猜你喜欢
    • 2018-12-12
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多