ruby-on-rails - 如何在 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
解决方案
要使用 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
推荐阅读
- java - 经典的 asp 和 webservices - 如何使它与 java 一起工作?
- laravel - 在 v-for laravel-vue 中显示
- node.js - 如何在mongodb查询中调用javascript函数
- selenium - 如何保存来自互联网的图片流?
- c# - 路由未初始化
- python - PyQt.QTableView 内容的单元测试
- ruby-on-rails - 狂欢::Image.create!- 无法创建
- sql - 字符出现之间的正则表达式匹配
- python - 从 Python 中的日期时间获取日期
- ms-access - 以编程方式显示浮动在表单上的功能区选项卡