[英]How to implement Ajax with will_paginate gem on Ruby on Rails
我想在我的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
要使用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代码段中获取了以下步骤: https : //gist.github.com/jeroenr/3142686
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.