0

我有两个模型(文件夹和文档)需要在一个视图中一起显示。但是,为了减少发送的查询数量,我仅在文件夹少于 12 个(我的:per_page)时才收集文档。虽然这工作正常,但我被困在一个特殊情况下,

当我的文档总数少于 12 个且文件夹少于 12 个但加起来超过 12 个时,分页失败。

下面是计算要显示哪个页面的代码,该页面f_page返回文件夹分页的页面并d_page返回文档集合的页码。

   def f_page(page_cnt, size)
    page_cnt.present? and size.nonzero? ? page_cnt.to_i <= (size/12 + (size%12==0 ? 0 : 1)) ? page_cnt.to_i : (size / 12 ) + (size%12==0 ? 0 : 1) : 1
  end

  def d_page(page_cnt, fc, dc)
    page_cnt = page_cnt.present? ? page_cnt : 1
    puts page_cnt
    dpg = 1 
    if (fc/12+1 == page_cnt.to_i)
      dpg = 1   
    elsif ((fc/12+1) < page_cnt.to_i)
      if (fc < 12)
        unless (dc <= 12)
          dpg = page_cnt
        else
          dpg = 1
        end
        else
          (fc/12 == 0) ? (dpg = page_cnt.to_i - (fc/12+1)) : (dpg = page_cnt.to_i - (fc/12))
        end
      end
      puts "dpg = #{dpg}"
      return dpg
    end

两者都一起收集和分页,这在视图中显示。

f = Folder.action_folder_collection(@action, current_user).paginate(:page => params[:page], :per_page => 12)
  if (f.count < 12)
    d = Document.action_document_collection(@action, current_user).paginate(:page => d_page(params[:page], total_folders, total_documents), :per_page => per_page-f.count)
  end
  collection << f
  collection << d
  @collection = collection.flatten.paginate(:page => 1,:per_page => 12,:total_entries => total)

我该如何解决?

4

1 回答 1

0

我刚刚解决了类似的问题。我的paginate_catalog_children助手接收 AR 集合或集合数组作为参数,并返回WillPaginate::Collection包含来自所有集合的元素的对象。

def paginate_catalog_children catalog_children, page
  per_page = 20
  if catalog_children.is_a? ActiveRecord::Relation
    catalog_children.paginate(:per_page => per_page, :page => page)
  else
    # paginating array of collections
    WillPaginate::Collection.create(page, per_page) do |pager|
      catalog_children_counts = catalog_children.map(&:count)

      result = []
      offset = pager.offset
      items_left = pager.per_page

      catalog_children.each_with_index do |collection, index|
        break if items_left == 0
        if catalog_children_counts[index] <= offset
          # skip this collection
          offset -= catalog_children_counts[index]
        else
          collection_items = collection.limit(items_left).offset(offset)
          result += collection_items
          items_left -= collection_items.size
          offset = 0
        end
      end

      pager.replace(result)
      pager.total_entries = catalog_children_counts.sum
      result
    end
  end
end
于 2013-04-14T09:08:12.517 回答