今天嘗試使用will_paginate插件實現分頁。
1. 按照官方文檔https://github.com/mislav/will_paginate/wiki/Installation安裝will_paginate插件。
在Gemfile中添加:
gem 'will_paginate', '~> 3.0.5'
然後在Project的路徑下運行:bundle install
出現錯誤:
查閱資料,原因是Rubygem官網被牆了。
解決辦法:
把Gemfile的第一句:
source 'https://rubygems.org'
改爲:
source 'http://ruby.taobao.org/'
再次運行bundle install,成功,顯示如下:
2.插件安裝成功後,修改對應的controller.rb文件。
把index方法中,
@posts = Post.all語句改爲
@posts = Post.paginate(:page => params[:page], :per_page => 10)
並在對應的indexj.html.erb中,加入:
<%= will_paginate @posts %>
隨後,在environment.rb文件中,加入:
require 'will_paginate'
在瀏覽器中即可查看分頁效果。
如果提示undefined method `paginate' ,試試重啓rails服務器。
3.定義分頁的樣式。
去http://mislav.uniqpath.com/will_paginate/下載樣式pagination.css,爲了方便我直接把代碼拷貝到application.css裏面。
修改index.view:
<%= stylesheet_link_tag "application"%>
<div class="apple_pagination">
<%= will_paginate @posts, :container => false %>
</div>
顯示效果: