前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails应用分页: Will Paginate

Rails应用分页: Will Paginate

作者头像
用户2183996
发布2018-06-28 11:06:02
3180
发布2018-06-28 11:06:02
举报
文章被收录于专栏:技术沉淀技术沉淀

Use will_paginate to Seperate Pages

It's a common practice to use pagination if there are too many stuff on your website, because no one want to scroll down to an endless page. And will_paginate is cool gem to solve this problem! Here is a simple guide to use.

Add Gem

First thing you need to do is to add will_paginate gem to you Gemfile. Just add gem 'will_paginate', '~> 3.0.5' to your Gemfile and run bundle install and restart your server.

Change controller

Say you want to add pagination for you post index page, then you just need a little change to index congtroller.

代码语言:javascript
复制
#without paginagtion
class PostsController < ApplicationController
    def index
        @posts = Post.all.order('created_at desc')
    end
end
代码语言:javascript
复制
#with pagination
class PostsController < ApplicationController
    def index
        @posts = Post.all.order('created_at desc').paginate(page: params[:page], per_page: 7)
    end
end

Add Pagination to View

Just add this line of code to your view page <%= will_paginate @posts %> and then that's it. You may also want to add some CSS to make it pretty. Here is the SCSS code for my pagination.

代码语言:javascript
复制
.pagination:before,
.pagination:after {
    content: " ";
    display: table;
}

.pagination:after {
    clear: both;
}

.pagination {
    text-align: center;
    margin: 0 0 3em 0;
    a, .previous_page, .current, .next_page {
        padding: .75em 1em;
        margin: 0 .5em;
        border-radius: .15em;
        line-height: 20px;
        text-decoration: none;
        background: $white;
        font-weight: 700;
        font-size: .7em;
        font-style: normal;
        color: $dark;
        &:hover {
            background: $highlight;
            color: $white;
        }
    }
    .current {
        background: $highlight;
        color: $white;
    }
    .disabled {
        color: #C0C0C0;
        &:hover {
            color: #C0C0C0;
            background: $white;
        }
    }
}

戳这看效果

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.06.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Use will_paginate to Seperate Pages
  • Add Gem
  • Change controller
  • Add Pagination to View
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档