2013-03-11 46 views
4

主持人:使用will_paginate沒有活動記錄

應用/演示/ games_presenter.rb

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加載ap高配車型以及PS /主持人/目錄/,控制器/,視圖/等內容添加到配置/ application.rb中:

config.after_initialize do |app| 
    app.config.paths.add 'app/presenters', :eager_load => true 
end 

我只是想知道我怎麼會去使用will_paginate對於上述案件? 。謝謝。

回答

8

@presenter.games假設是一個Array,嘗試:

# 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

+0

非常感謝您的回覆。但我錯了。在@games = @ presenter.games.paginate(params [:page],5)上的參數(2代表1)...你有什麼想法爲什麼? – kauschan 2013-03-11 22:12:48

+0

嘗試重新啓動您的Rails服務器。初始化程序可能未被加載。如果那不是,那麼檢查一下'@ presenter.games'是什麼。如果它是一個數組,'@ presenter.games.class.name'應該返回''Array「'。 – Sam 2013-03-11 22:18:57

+0

修復它..謝謝,它確實返回一個數組..但是我仍然不知道爲什麼它通過零(不能將零轉換爲整數) – kauschan 2013-03-11 22:34:20

1

我有同樣的問題,我找到了一些最簡單的解決方案。

創建文件的配置/初始化,只是要求「will_paginate /陣」爲:

require 'will_paginate/array'

您也可以要求它在其他任何適當的文件也。它可以在任何數組上工作。

希望它會有所幫助。

謝謝 - TechBrains