MVC Fundamentals
When starting Mod2 for Flatiron School, I had no idea of what an MVC could possibly be or what its purpose was. I was very much frightened by the idea of learning a whole different concept.
As the first week of Mod2 passed by, I was able to develop a basic understanding of MVC and realized that it wasn’t that much different from what I’ve learned in Mod1. In Mod1, we learned about object orientation and establishing relationships(one to many, many to many, etc.), to then learn about SQL and eventually Active Record. A huge portion of MVC depends on Active Record, specifically when creating models, and establishing relationships between those models. Before explaining MVC’s function, we should first know what an MVC actually is! MVC stands for Model, View, Controller. MVC allows the developer to create barriers to organize the code, allowing a developer to compartmentalize functionality.
Each characteristic of MVC explained in further detail:
Model: Encloses the data in our database and allows us to treat them as objects. For instance, Active Record plays the model role since it handles all of the logic and database communications. Also, it allows the developer to create, read, update and delete(CRUD) data.
- View: It’s known as the presentation layer because it’s what a developer would want to show on the browser. The views section interacts with HTML, CSS and Javascript. Depending on what the developer wants to display on the website, the view section may contain up to four html.erb files. These files are known as the index, show, edit, and new files. As mentioned before, depending on what the developer wants, a view folder can contain any number of html.erb files.
- Controller: This section handles browser requests and eases communication between the Model and View sections. Similar to Views, Controller contains methods that are related to those views files(index, show, etc).
- One thing to notice is that the MVC is located inside the /app directory when running
rails new AppName
When wanting to build a rails app, you don’t necessarily have to start with the MVC framework! Here’s an example of that:
- You can use this diagram as a way to guide you. Depending on who you are as a developer, you can choose to start with setting up your database first and then work your way through the MVC or start with your MVC first.
Benefits provided by an MVC framework:
- Allows for an asynchronous connection to the backend of your app
- Separation of concern between Views, Models, and Controllers
- Development of the application becomes fast.
- Easy for multiple developers to collaborate and work together.
- Easier to update the application.
- Easier to debug as we have multiple levels properly written in the application.
Other frameworks that use MVC besides Ruby on Rails:
- Angular
- AngularJS
- Laravel
- Django