Skip to content

Instantly share code, notes, and snippets.

@Joseph-N
Last active April 19, 2019 12:50
Show Gist options
  • Save Joseph-N/10128289 to your computer and use it in GitHub Desktop.
Save Joseph-N/10128289 to your computer and use it in GitHub Desktop.
Rails - Load more with jQuery and Ajax Code snippets - Tutorial link http://josephndungu.com/tutorials/rails-load-more-results-using-jquery-ajax
<div class="record" data-id="<%= user.id %>">
<p><b>ID: </b> <%= user.id %></p>
<p><b>Name: </b> <%= user.name %></p>
<p><b>Location: </b> <%= user.location %> </p>
<p><%= link_to 'Show', user %> | <%= link_to 'Edit', edit_user_path(user) %> | <%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %> </p>
</div>
<div class="container">
<%= render @users %>
</div>
<div class="load-more-container">
<!-- hide our loading gif image so that we show it when making ajax call via jquery -->
<%= image_tag "ajax-loader.gif", style: "display:none;", class: "loading-gif" %>
<%= link_to "Load More", users_path, class: "load-more" %>
</div>
// append the users partial to our div with class of container
$('.container').append('<%= escape_javascript(render(:partial => @users)) %>')
class User < ActiveRecord::Base
default_scope { order('created_at DESC') }
end
// when the page is ready for manipulation
$(document).ready(function () {
// when the load more link is clicked
$('a.load-more').click(function (e) {
// prevent the default click action
e.preventDefault();
// hide load more link
$('.load-more').hide();
// show loading gif
$('.loading-gif').show();
// get the last id and save it in a variable 'last-id'
var last_id = $('.record').last().attr('data-id');
// make an ajax call passing along our last user id
$.ajax({
// make a get request to the server
type: "GET",
// get the url from the href attribute of our link
url: $(this).attr('href'),
// send the last id to our rails app
data: {
id: last_id
},
// the response will be a script
dataType: "script",
// upon success
success: function () {
// hide the loading gif
$('.loading-gif').hide();
// show our load more link
$('.load-more').show();
}
});
});
});
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
# if the id params is present
if params[:id]
# get all records with id less than 'our last id'
# and limit the results to 5
@users = User.where('id < ?', params[:id]).limit(5)
else
@users = User.limit(5)
end
respond_to do |format|
format.html
format.js
end
end
.......
end
@mdfarhanjawed
Copy link

thanks!!

@RailsCod3rFuture
Copy link

How do you handle nil associations with AJAX? Lets say, we have a user with a profile that has a nil avatar. post.user.user_profile.avatar. What can I do to avoid a failing AJAX request, given that situation?

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