Rails: Download More Button with Ajax & Kaminari

I would like to create a "load more" ajax pagination, with Kaminari. I am using this code:

class BienvenueController < ApplicationController def index @articles = Admin::Article.page(1).per(2) respond_to do |format| format.html format.js end end end # Bienvenue#index <div class="container" style="min-width:<%= @width %>px"> <%= render "shared/articles" %> <%= link_to_next_page @articles, 'Load More', :remote => true, :id=>"load_more_link" %> 

 # Shared/articles <% @articles.each do |a| %> <article class="<%= a.rubrique.color %>"> <div class="sharing"> <%= image_tag "facebook-32.png" %> </div> <p class="color<%= a.rubrique.color %>"><i>Le <%= I18n.localize(a.created_at, :format => :long) %> par David Perrotin</i></p> <h1><%= a.titre %></h1> <div class="excerpt"> <%= a.chapo.html_safe %> </div> <div class="image"> <%= image_tag a.mainphoto.url(:medium), :width=>"100%" %> </div> <div class="contenu"> <%= a.contenu.html_safe %> </div> <div class="readmore"> <%= link_to "Continuer la lecture", article_path(a) %> </div> </article> <% end %> # index.js.erb $('.container').append("<%= escape_javascript(render 'shared/articles')%>"); $('#load_more_link').replaceWith("<%= escape_javascript(link_to_next_page(@articles, 'Load More', :remote => true, :id=>'load_more_link'))%>"); 

But the problem is that when I click "Download more", it always shows two identical articles, a partial one is never updated with two more articles, as I would like.

+6
source share
1 answer

I just ran into a problem that might help others. Depending on your version of jQuery, do not use replaceWith in #load_more_link in index.js.erb .

There is a regression ( http://bugs.jquery.com/ticket/13401 ) that empty replaceWith does nothing, so on the very last page of your set link_to_next will be empty by creating the line: $('#load_more_link').replaceWith(''); and thus will not replace the last β€œmore" button, so you will constantly load the last page of your dataset.

Fixed by updating jQuery version or using empty().html('...') instead of replaceWith.

+2
source

Source: https://habr.com/ru/post/943441/


All Articles