Rails Controllers — The C in MVC
What is a controller?
A controller is a Ruby class that inherits ApplicationController and has many methods just like any other class. At a high level, the controller is responsible for handling a request from the browser and sending a response.
The C in MVC
MVC stands for Model, View, Controller and it’s the architecture of our web app. It separates our wep app into different components. Models will handle the data and logic, Views handle how our data is shown, and Controllers manage the application. Today we’ll just talk about Controllers.
How it works
I have project called Tracoon, a web app that tracks raccoons spotted in Seattle neighborhoods and I’ll use this web app for my examples below.
If we visit localhost:3000/raccoons in our browser, it will send an HTTP request to the rails server. Upon receiving the request, rails will scan through each route defined in your routes.rb file to find one matching the request verb and URL combination. For a more in-depth look at Rails routes you can read my post here: https://medium.com/@tafby88/rails-routes-for-rookies-13d5fa2decdd
The Router instantiates a rails controller, and calls the appropriate method on it, e.g: RacoonsController.index.
In our example index action, we are retrieving all the raccoons from our database and storing them in the instance variable named @raccoons.
At the end of a controller action, by default rails will attempt to render an erb file with a name that corresponds to the action name. In our example it will try to render the index.html.erb file. The instance variable @raccoons is now available for use of the view.
The rails controller will now send the HTML rendered by the view as a response back to the browser.
You can think of a controller as the middleman between the model and the view. It’s a pretty important part to our rails app and will make sense of any HTTP request that is sent to your web app.
There is so much more that a controller can do, but these are just the basics. Next week, I’m going to talk about models and the role they play in the MVC pattern.
Here are some resources that I used while writing this blog, and I encourage you to read them as well!