2013-03-11 45 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