首页 > 解决方案 > 如何在 Ruby on Rails 上使用 will_paginate gem 实现 Ajax

问题描述

我想在我的 ruby​​ on rails 项目上实现 Ajax。我目前使用 will_paginate gem。每当我单击下一页时,整个页面都会重新加载,这是我不希望发生的。我怎样才能防止这种情况?我发现了一个类似的问题,但它对我不起作用。我猜是因为我使用的是 Rails 5.2.2?我不知道。

我的 index.html.erb 看起来像这样:

 <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>

这是我的controller.rb中的代码:

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

标签: ruby-on-railsajaxpaginationwill-paginate

解决方案


要使用 AJAX 进行分页而不是页面刷新,您需要在data-remote="true"所有分页链接中添加一个。

data-remote="true"是一个 Rails 助手,它将导致服务器将请求解释为 JS 而不是 HTML。

第一步,创建一个新的助手:

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

其次,paginate向 application_helper 添加一个方法。

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

然后,您可以替换它:

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

有了这个:

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

我从这个 GitHub Snippet 得到了这些步骤:https ://gist.github.com/jeroenr/3142686


推荐阅读