Skip to content

Creating REST Controllers

RyanDawkins edited this page Nov 9, 2014 · 1 revision

Overview

This is the page where we will describe how to create REST controllers when contributing to the application. We have created a base REST controller that we use.

Creating a new REST Controller

Let's create a rest controller named dog. We are assuming you have a model named Dog that has the property breed.

$ rails g controller dog
      create  app/controllers/dog_controller.rb
      invoke  erb
      create    app/views/dog
      invoke  test_unit
      create    test/controllers/dog_controller_test.rb
      invoke  helper
      create    app/helpers/dog_helper.rb
      invoke    test_unit
      create      test/helpers/dog_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/dog.js.coffee
      invoke    scss
      create      app/assets/stylesheets/dog.css.scss

First we should edit our tests for the REST Controller to go from this:

require 'test_helper'

class DogControllerTest < ActionController::TestCase
  # test "the truth" do
  #   assert true
  # end
end

To this!

require 'test_helper'

class DogControllerTest < ActionController::TestCase

  test "should get index for all" do
    get :index, :format => :json
    assert_response :success
  end

  test "should get show by id" do
    get :show, :format => :json, :id => 1
    assert_response :success
  end

  test "should post create" do
    post :create
    assert_response :success
  end

  test "should post update" do
    post :update, :format => :json, :id => 1
    assert_response :success
  end

  test "should get delete" do
    get :delete, :format => :json, :id => 1
    assert_response :success
  end

end

Next thing you need to do is edit the REST Controller file which should look like this:

class DogController < ApplicationController
end

There's two things we need to do here. We need to change the inherited controller to RestController and we need to implement the abstract methods. According to our our REST Controller base class we need to implement at least two methods: get_class and from_params. So let's do that!

class DogController < RestController

  def get_class
    Dog
  end

  def from_params
    params.permit(:breed)
  end
end

What this does..

  1. Our method get_class is expected to return the class that our model is in our example this is the Dog class.
  2. from_params returns a list containing the params that we want to allow our api to update and create a model with.

Finally we need to make additions to our routing file:

Rails.application.routes.draw do
  # ...

  get 'dog/' => 'dog#index'
  get 'dog/:id' => 'dog#show'
  post 'dog/create' => 'dog#create'
  post 'dog/:id/update' => 'dog#update'
  get 'dog/:id/delete' => 'dog#delete'

  # ...
end

Then run your tests and they should pass!

rake test
Clone this wiki locally