Rails + 将对列表演示者进行分页

Rails + Will paginate paginating a list presenter

今天我要展示已分页的列表中的项目:

users = User.order('name').paginate(:per_page => 10, :page => 1).map{|u| UserPresenter.new(e)}

问题是 users 不再是(在映射到我的演示者之后)一个用 will_paginate 魔法包装的数组,所以它不包含像 total_entries、per_page 这样的东西或页面,然后 will_paginate 助手在我看来不起作用 :S .

我应该如何对 post 已处理对象的列表进行分页?

我试过反其道而行之,但是如果我的 table 中有大量记录,那将非常痛苦,因为它会从已经检索到的大结果集中分页:

users = User.order('name').map{|u| UserPresenter.new(u)}.paginate(:per_page => 10, :page => 1)

提前致谢

也许我会尝试以这种方式创建一个 UserCollectionPresenter 和一个 UserPresenter

class UserCollectionPresenter
  include Enumerable

  delegate :paginate, to: :collection

  attr_reader :collection

  def initialize(collection)
    @collection = collection
    @_presentable_collection = collection.map { |user| UserPresenter.new(user) }
  end

  def each(&block)
    @_presentable_collection.each(&block)
  end

  def total_count
    @collection.limit(nil).offset(nil).count
  end
end

class UserPresenter
  def initialize(user)
    @user = user
  end

  private

  attr_reader :user
end

在控制器中,您应该发送分页的 AR 集合,稍后您可以使用分页。不确定你需要 will_paginate 的哪些方法,但我会考虑委托 "overriding" 它们或直接从 will_paginate 包含它们。

我建议您仍然对 will_paginate 使用 users,并为演示者添加另一个实例变量。

@users = User.order('name').paginate(:per_page => 10, :page => 1)
@presenters = @users.map { |u| UserPresenter.new(u) }