CRUD Basics

So we’ve got all the basics up and running, now it’s time to hook the models up to routes and let us add, edit, view and delete records from our database.

We’re going to follow the conventions of REST requests and responses/

Why REST?

REST is a convention that structures HTTP requests around data access and manipulations

REST been growing in popularity since 2005, and inspires the design of services, such as the Twitter API. This is due to the fact that REST allows you to interact with minimal overhead with clients as diverse as mobile phones and other websites.

The most important part of REST is the way it maps standard data access and manipulation actions onto URLs and HTTP verbs. This is typically how it works.

GET /tasks/	 		  -> LIST
POST /tasks/		  -> CREATE
GET /tasks/:id		  -> READ
PUT /tasks/:id		  -> UPDATE
DELETE /tasks/:id	  -> DESTROY

ActiveRecord is built to support REST and these CRUD (create, read, update, delete) type actions so it’s perfectly in synch with rest.

JSON

JSON (JavaScript Object Notation) is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.*

Typically for any REST API responses, we’ll use JSON (a nice data format) to send clean object-oriented responses back.

Add JSON to your project’s gem file like this

gem ‘json’

Then

bundle install

Let’s get going: Listing Tasks

Fire up your project and let’s add a basic route to return a list of all tasks

get ‘/tasks'  do
	Task.all.to_json
end 

Fire up your local server

shotgun config.ru

and visit the URL: http://localhost:9393/tasks

You should get a lot of content back. If you’re having trouble reading it, you can use a tool like JSON pretty print to help present it better

Reading Tasks

To add a read action in the REST/CRUD approach you’ll do the following

get '/tasks/:id' do
  Task.where(id: params['id']).first.to_json
end

Creating a Task

To add a create action in the REST/CRUD approach you’ll do the following.

post '/tasks' do
  task = Task.new(params)
 
  if task.save
    task.to_json
  else
    halt 422, task.errors.full_messages.to_json
  end
end

This lets you send a bunch of parameters through a POST method. The ruby code will create an object based on the params it receives and try to add it to the database.

If all goes well you’ll get that object back as a JSON object. Otherwise it’ll return an error that presents the validation information.

You can’t test a POST method from your browser (a browser will only send a GET request.) Instead we can use cURL to test it. It’s installed by default on OSX but if you’re on Windows you’ll need to install it first.

Once installed, open a terminal window and type the following at the command prompt:

curl -X POST -F 'name=test' -F 'list_id=1' http://localhost:9393/tasks

Updating a Task

To add an update action in the REST/CRUD approach you’ll do the following.

put '/tasks/:id' do
  task = Task.where(id: params['id']).first
 
  if task
    task.name = params['name'] if params.has_key?('name')
    task.is_completed = params['is_completed'] if params.has_key?('is_completed')
    
    if task.save
      task.to_json
    else
      halt 422, task.errors.full_messages.to_json
    end
  end
end

This requires an named ID parameter (that matches the id primary key in the table). Using this parameter it’ll look up the object in the database and if there’s a match we’ll be able to update it.

Then it’ll look to see if parameters have been passed and if they have the values will be updated.

If all goes well you’ll get that object back as a JSON object. Otherwise it’ll return an error that presents the validation information.

You can’t test a PUT method from your browser either. so we’ll use cURL again:

curl -X PUT -F 'name=updates' -F 'list_id=1' http://localhost:9393/tasks/1

Deleting data

To add an DELETE action in the REST/CRUD approach you’ll do the following.

delete '/tasks/:id' do
  task = Task.where(id: params['id'])
 
  if task.destroy_all
    {success: "ok"}.to_json
  else
    halt 500
  end
end

This requires an named ID parameter (that matches the id primary key in the table). Using this parameter it’ll look up and return the object from the database.

If the object (matched by ID exists), it’ll be destroyed and confirmed.

Otherwise it’ll return an error that presents the validation information.

You can’t test a DELETE method from your browser either. so we’ll use cURL again:

curl -X DELETE http://localhost:9393/tasks/1
×

Subscribe

The latest tutorials sent straight to your inbox.