简体   繁体   中英

How to implement Ajax with will_paginate gem on Ruby on Rails

I want to implement Ajax on my ruby on rails project. I currently use the will_paginate gem. Whenever I click for the next page, the whole page reloads, which I don't want to happen. How can I prevent this? I found a similar question but it didn't work for me. I guess it's because I am using Rails 5.2.2? I am not sure.

My index.html.erb looks like this:

 <div class="row justify-content-center align-items-center">
       <div class="page_info">
        <h5><%= page_entries_info @imports %></h5>
       </div>
 </div>
 <div class="row justify-content-center align-items-center">
       <div class="page_info">
        <h5><%= will_paginate @imports, :container => false %></h5>
       </div>
 </div>

Here is my code in my controller.rb:

class ImportsController < ApplicationController
  def index
     @imports = Import.all
     @imports = Import.paginate(:page => params[:page], :per_page => 5)   
  end

To paginate with AJAX instead of a page refresh, you'll need to add a data-remote="true" to all of the paginate links.

data-remote="true" is a rails helper that will cause the server to interpret the request as JS instead of HTML.

First step, create a new helper:

module RemoteLinkPaginationHelper
  class LinkRenderer < WillPaginate::ActionView::LinkRenderer
    def link(text, target, attributes = {})
      attributes['data-remote'] = true
      super
    end
  end
end

Second, add a paginate method to the application_helper.

module ApplicationHelper
  def paginate(collection, params= {})
    will_paginate collection, params.merge(:renderer => RemoteLinkPaginationHelper::LinkRenderer)
  end
end

Then, you can replace this:

<div class="row justify-content-center align-items-center">
  <div class="page_info">
    <h5><%= will_paginate @imports, :container => false %></h5>
  </div>
</div>

with this:

<div class="row justify-content-center align-items-center">
  <div class="page_info">
    <h5><%= paginate @imports, :container => false %></h5>
  </div>
</div>

I got these steps from this GitHub Snippet: https://gist.github.com/jeroenr/3142686

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM