Skip to content

Instantly share code, notes, and snippets.

@zolzaya
Last active February 2, 2021 02:01
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save zolzaya/7211962 to your computer and use it in GitHub Desktop.
Save zolzaya/7211962 to your computer and use it in GitHub Desktop.
Most easy "load more" behavior implementation for Kaminari.

In your view:

<%= link_to "Load more", posts_path(@posts, page: @posts.current_page+1), id: "load-more-posts", remote: true %>

In your controller:

respond_to :html, :js, only: [:index]

def index
  @posts = Post.recent.page(params[:page]).per(10)
  respond_with @posts
end

In your index.js.erb

$("#posts-container").append("<%= j(render(partial: "posts", collection: @posts)) %>");

<% if @posts.last_page? %>
  $("#load-more-posts").hide();
<% else %>
  # hide loader indicator
  $("#load-more-posts").attr("href", "<%= posts_path(@posts, page: (@posts.current_page+1)) %>");
<% end %>
@polgasull
Copy link

Hello I receive this error:

ActionController::UnknownFormat (ActionController::UnknownFormat)

@cartond
Copy link

cartond commented Dec 28, 2018

Hello I receive this error:

ActionController::UnknownFormat (ActionController::UnknownFormat)

Can you open an issue with some of your code? I can try to help.

@Vova11
Copy link

Vova11 commented Dec 30, 2018

Hi this was working for me ...
$('#load-more-posts').replaceWith("<%= escape_javascript(link_to_next_page(@products, 'Load more', :remote => true, :id=>'load-more-posts' ))%>");

Any idea how to add ?page=XX to url? Code bellow is working but only for the first click... second click does not add ?page=XX to url....

$(document).on('turbolinks:load', function() {
$('#load_more_link').on('click', function() {
url = $(this).attr('href');
window.history.pushState(url, window.title, url);
});
});

@nv-hung
Copy link

nv-hung commented Jun 25, 2019

Oh. I tried. I think we need loop at index.js.erb, because transfer only to the second page. But I don't know how to write a loop statement combining Rail and js. Can you guide me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment