DEV Community

Zoe Mendez
Zoe Mendez

Posted on

Application Controllers for Beginning Ruby Developers

What are Application Controllers?

When beginning to build your API you will need to set up the controllers that allow you to fetch your API data. Here is where you set up what data you want to be grabbed when you use a specific tag in the fetch.

How do the Application Controllers work??

Well instead of using the initial def in ruby, you are going to use what ever method that you are going to be using. You also must create a function that will generate that information.

Get

=begin
table with data: schools
includes: 
name
grades
principal
rating
=end

get "/schools" do
variable = School.all
variable.to_json
end

Enter fullscreen mode Exit fullscreen mode

Above you can see that I created a get request by the method initiation being get. What I did above allows me to grab all the data associated to the schools table. The fetch URL for me would look like http://localhost:9000/schools.

Post

=begin
table with data: schools
includes: 
name
grades
principal
rating
=end

post "/schools" do 
variable = School.create(
name: params(name),
grades: params(grades),
principal: params(principal),
rating: params(rating)
)
variable.to_json
end
Enter fullscreen mode Exit fullscreen mode

Same as before, the method is initiated with the fetch request that I am creating for API. In this method, you can see that I used the .create attribute that allows me to create a new element to be added to my table.

Patch

=begin
table with data: schools
includes: 
name
grades
principal
rating
=end

patch "/schools/:id" do 
variable = School.find(params(id)
variable.update(
:principal => params(principal)
)
variable.to_json
end
Enter fullscreen mode Exit fullscreen mode

The patch method, I use a .find to find the particular object that I'm trying to make adjustments to. Then I call .update on that object to update a specific part on the object. Above I choose to do the principal because that was the most likely part of the object to be updated. The fetch URL for this particular call would be http://localhost:9000/schools/:id. Then you would interpolate the id of the school into the URl.

Delete

=begin
table with data: schools
includes: 
name
grades
principal
rating
=end

patch "/schools/:id" do 
variable = School.find(params(id))
variable.destroy
variable.to_json
end
Enter fullscreen mode Exit fullscreen mode

Like the patch request, the fetch URL stays the same. In the method you can see that I'm finding the object in which I intend to remove, and then calling the .destroy attribute in order to remove that idea from my database and the site.

This is the simple base on the building the CRUD controllers on an API. Feel free to use Active Record Basics to help with any extra questions I didn't cover.

Top comments (0)