So I'm trying to create a load more button (not infinite scroll although some simple js tweaks could make it so). I'm using the will_paginate gem in Rails 5.
Its currently all working as expected except when I click load more it loads the next page posts twice e.g: Load more > Post 4, Post 5, Post 6, Post 4, Post 5, Post 6
FYI my 'posts' are @links:
links_controller.erb
def index
@links = Link.order('created_at DESC').paginate(:page => params[:page], :per_page => 3)
respond_to do |format|
format.html
format.js
end
end
views/links/index.html.erb
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page', :remote => true if @links.next_page %>
</div>
<% end %>
pagination.js.coffee
$ ->
$('.next_page').on 'click', (e) ->
e.preventDefault()
url = $(this).attr('href')
$.getScript(url)
index.js.erb
$('.link-wrap').append('<%= j render(@links) %>');
<% if @links.next_page %>
$('.next_page').attr('href','<%= links_path(:page => @links.next_page) %>');
<% else %>
$('.more').remove();
<% end %>
For the life of me I can't figure out why it would be rendering the links twice when 'load more' is clicked. This seems like a really simple thing but I'm struggling.
So it was a stupid error of course.
Remove the line on index.html.erb:
:remote => true if @links.next_page
So now it looks like this:
<div class="link-wrap">
<%= render @links %>
</div>
<% if @links.next_page %>
<div class="link more">
<%= link_to 'Load More', links_path(:page => @links.next_page), :class => 'next_page' %>
</div>
<% end %>
All works fine now!
If you check the server console, you can actually see two requests coming in, one triggered by your :remote => true
enabled link and other from your custom ajax. Actually you don't need any js
to make this work. Just remove that click function from your pagination.js.coffee
or remove :remote => true
from the link. After all both are doing the same thing. Hope this will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With