Restful Routing
This week in the Flatiron School’s curriculum we started learning about MVC architecture. This includes setting up controllers and assigning routes to them. These routes determine what happens when users visit certain pages on your site and the destinations that forms use to post new data. One of the difficulties with these routes is what to name them. How is that a problem? Freedom of choice. Who doesn’t love that?
As long as the “action” attribute on your form and the route match up, everything is good. Right? Well, yes and no. Yes in the sense that your routes will work and your forms will be sending their data to the right places. Wrong in that you will be the only one to know how to connect with your web application.
Say that you wanted to build your own API connecting to your web application. Whenever someone wanted to connect to your API, they would have to know what you named your routes. Ok, no big deal. Well, what if I do the same thing and name my routes something completely different? And then, two more developers do the same thing? Now you’ve got a handful of web apps each with their own unique routes. How will you remember which routes go to which app. You won’t.
So, what are we supposed to name our routes then?
Phil Karlton said that “There are only two hard things in Computer Science: cache invalidation and naming things.”
Well, luckily, the hard work has been done for us. There are seven standard paths we can use for our controllers and they line up with the HTTP verbs as well as CRUD methods.
Below is a table of those seven paths along with their associated HTTP verbs, their purpose and the corresponding ActiveRecord methods and SQL statements.
The ‘Index’ and ‘Show’ routes are all about retrieving information and presenting it to the user. It just depends on if you want to show ALL of something or just one thing.
‘Create’ and ‘New’ are used for ummm…. creating new things. ‘Create’ will make the actual object and save it to a database, if that’s your thing. The ‘New’ route will present you with the form to create that new thing.
Similarly, ‘Update’ will update an existing object and the ‘Edit’ route will present you with the form for changing something that already exists.
‘Destroy’ does just what it says. It will delete an object.
Simple. Easy to remember. They sound like the things that they do. Great. Seven less things for me to think about and remember.
Because we’ve all agreed on there being standard routes now there is no guesswork when it comes to creating routes for our web apps or connecting to other developers’ web applications.