簡體   English   中英

如何在Ruby on Rails上使用will_paginate gem實現Ajax

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM