2014-11-28

Rails : multi_paginate

source at : https://github.com/mislav/will_paginate/issues/351

and fix to multiple type :P

just source code (add to like ** application_controller.rb ** )

def multi_paginate(models, page, per_page)
  WillPaginate::Collection.create(page, per_page) do |pager|
    models.keep_if {|m| m.count > 0 }
    pager.total_entries = 0
    counts = []
    offsets = []
    limits = []
    for model in models
      pager.total_entries += model.count
      counts << model.count
      offset = pager.offset - offsets.sum
      offset = offset>model.count ? model.count : offset 
      offsets << (offset < 0 ? 0 : offset)
    end
    result = []
    for i in 0...models.count
      limits << pager.per_page - result.length
      result += case models[i]
      when ActiveRecord::Relation
        models[i].limit(pager.per_page - result.length).offset(offsets[i]).to_a
      when Array
        models[i][offsets[i]..(offsets[i] + pager.per_page - result.length)].to_a
      when Hash
        models[i].to_a[offsets[i]..(offsets[i] + pager.per_page - result.length)].to_a
      end
    end
    pager.replace(result)
  end
end

then use at controller like

 #source , page , per_page
 @orders = @paginate = multi_paginate(
   [@incoming_order , @outgoing_order , @redis_roder] ,
   params[:page].to_i.zero? ? 1 : params[:page].to_i.abs ,
   30
 ) 

then view

<% @orders.each do |order| case order ; when IncomingOrder %>
  ...view for IncomingOrder
<% when OutgoingOrder %>
  ...view for OutgoingOrder
<% when Array %>
  ...view for Array ... (Ruby or custom class)
<% end %>

hmmm... it's all & fave fun :)

沒有留言:

張貼留言