Rails - Load More Results Using Jquery & Ajax
08 Apr 14
In this tutorial, I will try and explain a very simple way on how to go about implementing a simple load more button which fetches for records using jquery, ajax in a rails application
Maybe you have seen how twitter's or facebook's style of loading older posts. They have a very nice technique of helping the user load older posts. We will try and create a similar functionality in a rails application. This tutorial assumes you have some basic knowledge with rails and jquery.
You can view a demo app made using this tutorial
on heroku, and you can also clone it on github.
So, for this tutorial I have scaffolded a user model to get up fast and running and my index.html.erb looks like so
In my user.rb file I am fetching records with the latest record fetched first
Next, in my users partial, I pass in the id of each record and store it in a html5 data attribute called id.
I then use jquery to get the last id of the record and make an ajax request to the server with the last id
In my users controller's index action, I test whether the id param is present and if so query for records with id lower than the last id we sent with ajax and limit the results to 5
We now need a file to respond to the js format. With this we create a file called index.js.erb which renders the user partial with the @users results
And thats it! your good to go! This is all you need to do a simple load more with jquery and ajax. If you have any problems, check the
source code and see if you can find any differences.