Skip to content

3.2. Companies Controller

Nicolas Erlichman edited this page Aug 18, 2022 · 4 revisions

Now that we have the base model set up, we will create a controller with a few endpoints to handle the create, read, update and delete operations.

We will run this command that does the job for us:

foo@bar:~$ rails generate controller Api::Company
      create  app/controllers/api/company_controller.rb
      invoke  test_unit
      create    test/controllers/api/company_controller_test.rb

We go now to the file app/controllers/api/company_controller.rb.

Replace the parent class with ApiController:

class Api::CompanyController < ApiController

Every public method (actions) we create here can be attached to a REST API route, so we will have 4 actions (create, show, update and destroy). show is Rails convention for the READ operation.

Create

We will create an endpoint to allow users to create a company.

Let's add this block to the controller

def create
  company = Company.create!(company_params.merge(user: current_user))
  render json: company
end

private

def company_params
  params.require(:company).permit(:name, :phone, :entity)
end

Read

We will create an endpoint to allow users to get their company information.

Let's add this block to the controller:

def show
  render json: current_user.company
end

Update

We will create an endpoint to allow users to update their company information.

Let's add this block to the controller:

def update
  company = current_user.company
  company.update!(company_params)
  render json: company
end

Destroy

We will create an endpoint to allow users to destroy the company.

Let's add this block to the controller:

def destroy
  current_user.company.destroy!
  head :ok
end

We have everything ready to be attached to API endpoints.

Let's go to the file config/routes.rb now.

Rails provides a simple way to specify routes for our endpoints. We can add this block as follows:

Rails.application.routes.draw do
  ...
  namespace :api, defaults: { format: :json } do # we tell Rails the default format of our API is json
    resource :company, only: %i[show update create destroy]
  end
  ...
end

If we run the command rails routes we should get the routes we just added:

foo@bar:~$ rails routes
api_companies GET    /api/company(.:format)                    api/companies#show {:format=>:json}
              PATCH  /api/company(.:format)                    api/companies#update {:format=>:json}
              PUT    /api/company(.:format)                    api/companies#update {:format=>:json}
              DELETE /api/company(.:format)                    api/companies#destroy {:format=>:json}
              POST   /api/company(.:format)                    api/companies#create {:format=>:json}

Yay 🎉! We have our Rails API set up!

Now we should be able to start hitting our endpoints from Postman.

Next: 4.1 Projects Model

Clone this wiki locally