Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Pagination in Rails Using will_paginate Gem

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 514
    Comment on it

    Hi Friends,

    Today I am going to tell you how we can integrate pagination in rails. First let's know why pagination is required in an application.

    Pagination is fetching data in batches and rendering one batch  at a time. It is necessary because of the following reasons:

    1. If there is a great amount of data, its processing may cause the server down.

    2. Rendering so much of data will not be user friendly.

    3. Rendering so much of data may also cause the web page crash.

    Now in rails we have so many already built gems that makes it very easy for developers to integrate pagination. Few of them are:

    a) paginate
    b) will_paginate
    c) kaminari

    Today I am going to discuss about will_paginate gem.

    Using will_paginate gem:

    First you need to add this to your Gemfile

    gem 'will_paginate', '~> 3.1.0'
    

    Now run bundle

    bundle install


    Now in whichever model you want to integrate pagination, you can just fetch the records by passing the page and per_page like this

    @articles = Article.paginate(page: params[:page], per_page: params[:per_page])

    You can also set the default per_page value in your model so that you don't need to pass the per_page value every time in query

    # For setting per_page in Article model
    class Article
      self.per_page = 10
    end
    
    # For setting per_page Globally
    WillPaginate.per_page = 10
    


    It also works on active record collections so you can add paginate on filtered records like this:

    Article.where(published: true).paginate(page: params[:page], per_page: params[:per_page])

    Thus till now we have integrated the pagination at server level, now to add pagination on view you can add this to the view file, it will automatically add the pagination with numbers in your view, you can customize it's css according to your wish

    <%= will_paginate @articles %>


    Hope you liked it.

     

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: