RESTful Routes in Rails
A quick talk about REST.
Before the Dive:
REST (REpresentational State Transfer) is the current standard concerning how web apps should be handling their URLs. To have clean URLs was the byproduct but their function was standardizing how HTTP verbs connected with the URLs. It made it much easier to understand what kind of data was being accessed by just the URL as well as understanding what resources they were accessing.
Before we jump into rest we must quickly touch upon the concept of CRUD.
Create: Submitting a new blog post talking about REST.
Read: You, the reader happening upon this blog and once finishing it, finding hundreds of spelling mistakes.
Update: Me furiously editing all the spelling mistakes, fixing them, and submitting it back.
Destroy: Me finding my spelling to be appalling and deleting the whole post.
REST:
With that all too real fictional example of CRUD, we can shift the topic to REST. Firstly, here is what it looks like.
Index: ‘GET’ — ‘/blogs’ — Shows all the blog posts.
Show: ‘GET’ — ‘/blogs/:id’ — Show a single blog post
New: ‘GET’ — ‘/blogs/new’ — Create a new blog post.
Create: ‘POST’ — ‘/blogs’ — Post(create) a new blog post.
Edit: ‘GET’ — ‘/blogs/:id/edit’ — Edit a particular blog post.
Update: ‘Patch/Put’ — /blogs/:id’ — Update the newly edited blog post.
*Destroy:* ‘Delete’ — /blogs/:id’ — Destroy your lovely blog post.
**Now Delete is not officially supported by the HTML standard and protocol. Most frameworks get around this in different ways. Rails sends this as a POST request and attaches a delete method in forms to differentiate it from a typical POST request.**
Now the first part is the action that handles the request. In rails, the controller handles each part of the convention as an action. Rails and its magic connects the action to the HTTP verb and correctly sends data throughout the app. The second part is the HTTP verb associated. The third part demonstrates what the URL should look like with each action. As you can see there are seven actions. It is easy to recognize which CRUD action connects with each route from querying from the database to removing a record.
HTTP Verbs
GET: Retrieves any info requested from the uri.
POST: Send data to the server, usually to make a new record in the database.
PATCH/PUT: Update existing records in the database.
Delete: Deletes a record from the database.
With this quick dive into RESTful conventions, may your coding endeavors bring you peace.