Repository navigation
4.2 Projects Controller
We have our Project model but we are missing a controller to perform actions. We will create a controller with a few endpoints to handle the create, read, update and delete operations.
We will run the following command:
foo@bar:~$ rails generate controller Api::Project
create app/controllers/api/project_controller.rb
invoke test_unit
create test/controllers/api/project_controller_test.rbWe go now to the file app/controllers/api/project_controller.rb.
Replace the parent class with ApiController:
class Api::ProjectController < ApiControllerWe will create an endpoint to allow users to create a project for their company.
Let's add this block to the controller
def create
project = Project.create!(project_params.merge(company: current_user.company))
render json: company
end
private
def project_params
params.permit(:name, :description, :start_date)
endWe will create an endpoint to allow users to get their company projects information.
Let's add this block to the controller:
def show
render json: current_user.company.projects
endWe will create an endpoint to allow users to update one of their company projects information.
Let's add this block to the controller:
def update
company = current_user.company
company.update!(company_params)
render json: company
endWe will create an endpoint to allow users to destroy a project.
Let's add this block to the controller:
def destroy
current_user.company.destroy!
head :ok
endWe 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
...
endIf we run the command rails routes we should get the routes we just added:
foo@bar:~$ rails routes
api_companies GET /api/project(.:format) api/project#show {:format=>:json}
PATCH /api/project(.:format) api/project#update {:format=>:json}
PUT /api/project(.:format) api/project#update {:format=>:json}
DELETE /api/project(.:format) api/project#destroy {:format=>:json}
POST /api/project(.:format) api/project#create {:format=>:json}