Rails应用分页: Will Paginate

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.

#without paginagtion
class PostsController < ApplicationController
    def index
        @posts = Post.all.order('created_at desc')
    end
end
#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.

.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;
        }
    }
}

戳这看效果

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区