Begin with ajax and jquery combined with rails, I am trying to create a "load more" link in the bottom of my user index page. My user index page should display the 10 first users, then clicking the link it loads the next 10 users on the bottom of the user div, etc.. I use Kaminari for pagination.
I started with the following code:
User_controller.rb
def index
@users = User.page(params[:page]).per(10)
end
User/index.html.erb
<div id="users">
<%= render :partial => @users %>
</div>
<%= link_to "Load more", "#", :class => "next" %>
_user.html.erb
<div id="box">
<%= link_to full_name(user), user %>
</div>
application.js
I found this snippet (credit: here) trying to fit it with my need:
function loadMore(pageNo) {
var url = '/users?page=';
$.get(url + pageNo, function(response) {
$("#users").append(response);
});
}
$(document).ready(function() {
var currPage = 1;
$("a.next").click(function() {
loadMore(++currPage);
});
});
I works perfectly except it loads all the page layout with the next results not only the box div in my _user partial How can I manage this? Did I have to create an index.js.erb (something like: page.insert_html :bottom, :users, :partial => @users but in jquery, if so how can I do it)?
Thanks for your help
You should create an own action for this, associated with it's own view. Then, be sure to disable rendering of the layout:
You shouldn't need to create another action for it. I would use unobtrusive javascript. Try something like this:
User_controller.rb
you shouldn't need to change anything here, just make sure the controller responds to js
User/index.html.erb
User/index.js.erb
That should be all that is needed to get it working. Of course you can add some javascript to insert a loading icon when the link is clicked or whatever. Note: I haven't tested this exact implementation, so there may be some errors, but you should be able to get the idea