2013-03-11 6 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 사용에 대한 갈 수있는 방법을 알고 케이스? .고맙습니다. @presenter.games 가정

답변

8

가 배열이며,이 시도 :

# 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

+0

레일 서버를 다시 시작하십시오. 이니셜 라이저가로드되지 않았을 수 있습니다. 그게 아니라면'@ presenter.games'가 무엇인지 확인하십시오. 그것이 배열이라면,'@ presenter.games.class.name'는''Array "'를 리턴해야합니다. – Sam

+0

그걸 고쳤어. 고마워. 배열을 반환 해. 그럼에도 불구하고 나는 왜 그것이 0으로 전달되는지 모른다. (Integer로 nil을 변환 할 수 없다.) – kauschan

1

같은 문제가 있으며 가장 간단한 해결책을 찾았습니다.

파일 설정/초기화를 만들고 마찬가지로 'will_paginate/배열'이 필요합니다 또한 당신은 또한 다른 적절한 파일을 필요로 할 수

require 'will_paginate/array'

합니다. 모든 배열에서 작동합니다.

희망이 있으면 도움이 될 것입니다.

감사합니다. TechBrains