[英]How to implement Ajax with will_paginate gem on Ruby on Rails
I want to implement Ajax on my ruby on rails project. 我想在我的ruby on rails项目中实现Ajax。 I currently use the will_paginate gem.
我目前使用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?
我猜是因为我正在使用Rails 5.2.2? I am not sure.
我不确定。
My index.html.erb looks like this: 我的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>
Here is my code in my controller.rb: 这是我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. 要使用AJAX进行分页而不是刷新页面,您需要向所有分页链接添加
data-remote="true"
。
data-remote="true"
is a rails helper that will cause the server to interpret the request as JS instead of HTML. data-remote="true"
是Rails助手,它将使服务器将请求解释为JS而不是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. 其次,将
paginate
方法添加到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 我从以下GitHub代码段中获取了以下步骤: https : //gist.github.com/jeroenr/3142686
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.