Creating a Rails API and Making Requests with jQuery AJAX

This post walks through the creation of a basic Rails API and how to query the API with jQuery AJAX. Start by creating a new Rails project called api_ajax, changing into the project directory, and creating a Post MVC with title and body attributes:

$ rails new api_ajax
$ cd api_ajax
$ rails g resource Post title body:text
$ rake db:migrate

Seed the database with 20 posts, so we can run some example queries:

# db/seeds.rb
20.times do |counter|
  Post.create(title: "Title-#{counter+1}", body: "Body-#{counter+1}")
end

Make a model class method that takes a two numbers as parameters and returns all Post objects with id’s between the numbers.

# models/post.rb
class Post < ActiveRecord::Base
  attr_accessible :body, :title
  def self.posts(lower_bound_id, upper_bound_id)
    Post.where("id > ? AND id < ?", lower_bound_id.to_i, upper_bound_id.to_i)
  end
end

Create an API that takes a lower_bound_id and upper_bound_id and returns a JSON response with the posts between the two ids. Also create a route to access the controller action.

# controllers/posts_controller
class PostsController < ApplicationController
  def posts_api
    respond_to do |format|
      format.json do
        lower_bound_id = params[:lower_bound_id]
        upper_bound_id = params[:upper_bound_id]
        @result = Post.posts(lower_bound_id, upper_bound_id)
        render json: @result
      end
    end
  end
end

# config/routes.rb
ApiAjax::Application.routes.draw do
  resources :posts
  match "posts_api" => "posts#posts_api"
end

Make a request in the browser to make sure the API is working properly: http://localhost:3000/posts_api.json?lower_bound_id=4&upper_bound_id=9

Create a view for the posts table action, so we have a location to put the form that will make the AJAX request.

# controllers/posts_controller
def posts_table
  respond_to do |format|
    format.html
  end
end

# config/routes.rb
match "posts_table" => "posts#posts_table"

Create a form with a fields for lower bound id and upper bound id and a button that will be used to trigger the request to the server. Also add a blank table that we can add rows to after we make the AJAX request:

<%#views/posts/posts_table.html.erb%>
<form>
  Lower bound id: <input type="text" id="lower_bound_id"><br />
  Upper bound id: <input type="text" id="upper_bound_id"><br />
  <input type="submit" value="Submit">
</form>

<table>
  <th>
    <td>Title</td>
    <td>Body</td>
  </th>
</table>

Add some CoffeeScript that will fetch the lower_bound_id and upper_bound_id when the Submit buttom is clicked, make an AJAX request to the Rails controller, and create a table that summarizes the results.

class Posts
  this.data_table = (table, data) ->
    for post in data
      row =
        "<tr>
          <td>#{post.title}</td>
          <td>#{post.body}</td>
        </tr>"
      table.append(row)

$ = jQuery
$ ->
  $('#posts_button').click ->
    lower_bound_id = $('#lower_bound_id').val()
    upper_bound_id = $('#upper_bound_id').val()
    $.ajax
      url: "/posts_api"
      type: 'GET'
      data: {lower_bound_id: lower_bound_id, upper_bound_id: upper_bound_id}
      success: (data) ->
        Posts.data_table($('table'), data)
      error: ->
        alert "Something went wrong"

Rails APIs are a powerful way to expose data to client side applications. Effective use of APIs can also encourage developing code that is loosely coupled, easily testable, and SOLID. jQuery’s ajax is an effective way to make JSON requests and use data in client-side applications.

Advertisements

5 thoughts on “Creating a Rails API and Making Requests with jQuery AJAX

    • Thanks for the comment. I’ll try to find some time to update this post, but I don’t think the new version of Rails will change much… posts_button is a HTML ID element on the page. It’s made by the Rails form. Thanks for the comment!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s