Controllers
We will create controllers named Meetings
and Bookings
. Navigate into the controllers
directory and run:
rails generate controller Meetings
rails generate controller Bookings
In your file tree, you should see the new controller.
Notice: In our Model, we use singular (Meeting), and in our Controller, we use the plural (Meetings).
Route
Once we have done with our Models and Controller, we'll need to establish the routes:
Rails.application.routes.draw do
defaults format: :json do
resource :meetings
resource :bookings
end
end
In our routes will be returning as the format json defaults format: :json do
After we set up our routes, you could run the command rails routes
, and you should see something similar to this.
Action Controller.
Inside meetings_controller.rb
we going stubbed out actions for index
, show
, create
and destroy
.
class MeetingsController < ApplicationController
def index
meetings = Meeting.all
render json: meetings
end
def show
meeting = Meeting.find(params[:id])
render json: meeting
end
def create
meeting_params = params.require(:meeting).permit( :title, :time_meeting, :start_date, :end_date, :start_time, :end_time)
meeting = Meeting.new(meeting_params)
meeting.save
end
def destroy
meeting = Meeting.find(params[:id})
meeting.destroy
end
end
Explain:
Action index
.
- The
index
actions will show all the meeting - As you can see, when you run the command
rails routes
-
Verd
(GET
) is the request of the API. -
URI
(/meetings
) is the link of the API. -
Controller
(meetings
) andAction
(index
) are when you run the API link(http://localhost:3000/meetings
), it will run into themeetings_controller.rb
file and run actionindex
.
-
def index
meetings = Meeting.all
render json: meetings
end
And in my booking_controller.rb
, 3 actions are index
, show
, create
.
class BookingsController < ApplicationController
def index
bookings = Booking.all
render json: bookings
end
def show
booking = Booking.find(params[:id])
render json: booking
end
def create
booking_params = params.require(:booking).permit(:name, :date, :time, :email, :message)
@booking = Booking.new(booking_params)
@booking.save
end
end
With the controller are done, and the routes are set up, we can be able to run rails s -p 3001
; the link will be http://localhost:3001/
Adding Data
Our data is empty right now, so it won't return anything. So I will create meeting
data with Postman.
1
First, open Postman and enter this link
http://localhost:3001/meetings
intoEnter request URL
. Because we will create a meeting, so we have to choose the methodPOST
.Second, click on
Body
, in the Beautify chooseraw
andJSON
.
After all, it will look like this:
- And type this data inside.
{
"title": "60 minutes meeting",
"time_meeting": "60",
"start_date": "2020-11-24",
"end_date": "2020-11-26",
"start_time": "01:00:00.000",
"end_time": "06:00:00.000"
}
It will look like this:
- Now you should be able to click
Send
, which will be creat the data for us.
2
Top comments (0)