[英]Advanced active record query, or a way to use will_paginate with an array
[英]Using will_paginate without active record
主持人:
class GamesPresenter
attr_reader :games, :next_page, :previous_page
def initialize json
@games = json['machine-games']
paging = json['paging']
if paging && paging['next']
next_page_query = paging['next'].match(/\?.*/)[0]
@next_page = "/machine_games/search#{next_page_query}"
end
if paging && paging['previous']
previous_page_query = paging['previous'].match(/\?.*/)[0]
@previous_page = "/machine_games/search#{previous_page_query}"
end
end
end
控制器動作:
def show
# ...
@presenter = GamesPresenter.new(json)
end
觀點:
<% @presenter.games.each do |game| %>
...
<% end %>
<%= link_to "Previous", @presenter.previous_page %>
<%= link_to "Next", @presenter.next_page %>
並且為了告訴Rails加載apps / presenters /目錄以及models /,controllers /,views /等,將其添加到config / application.rb:
config.after_initialize do |app|
app.config.paths.add 'app/presenters', :eager_load => true
end
我想知道如何在上述情況下使用will_paginate? 。謝謝。
假設@presenter.games
是一個數組,試試這個:
# Gemfile
gem 'will_paginate'
# /config/initializers/will_paginate_array.rb
require 'will_paginate/collection'
Array.class_eval do
def paginate(page = 1, per_page = 15)
page = 1 if page.blank? # To fix weird params[:page] = nil problem
WillPaginate::Collection.create(page, per_page, size) do |pager|
pager.replace self[pager.offset, pager.per_page].to_a
end
end
end
# /app/controllers/games_controller.rb
def show
@presenter = GamesPresenter.new(json)
@games = @presenter.games.paginate(params[:page], 5)
end
# /app/views/games/index.html.erb
<% @games.each do |game| %>
...
<% end %>
<%= will_paginate @games %>
這基本上將.paginate
方法添加到所有數組。 有關這方面的更多文檔,請訪問https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/collection.rb
我有同樣的問題,我發現了一些最簡單的解決方案。
創建文件配置/初始化程序,只需要'will_paginate / array':
require 'will_paginate/array'
您也可以在任何其他適當的文件上要求它。 它適用於任何陣列。
希望它會有所幫助。
謝謝 - TechBrains
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.