In this series of lessons, we are going to take a deeper look into how Rails applications work together.
When we were building your Ideator app, we came across words and files that have models, views, and controllers. These three things are extremely important in Rails applications.
Ruby on Rails is an MVC Framework. MVC stands for Model View Controller. The Model, View, and Controller each has seperate responsibilities, but work together in the application:
The model manages behaviors and data of the application.
It can respond to requests for information
Idea
, the model is responsible for taking care of this taskIdea.find(params[:id])
achieves this task. find
is a method that tells the model to find the object with the id
of the integer passed inside the parenthesis.Idea.find(4)
tells the model to find the Idea
with the id
of 4
.It can respond to instructions to change the information
Idea
s, the model is responsible for taking care of this taskThink of the model as the reliable guy who is responsible for fetching information and changing information.
The view is responsible for displaying the user interface. It can show data from the model and display it on the screen for users to see.
In your Ideator application, we wrote a lot of HTML code (in files such as index.html.erb
). Notice how index.html.erb
is located within the views
folder. The views
folder typically contains HTML files that contain content for users to see.
The controller is the middleman between the model and the view. It is responsible for handling user requests and logic.
Interact with model
Idea.find(params[:id])
in our controller. Idea.find(params[:id])
is a call to the model to fetch an Idea
. Like this, the controller can interact with the model.Receive events from the outside world (usually through views)
Idea
, we are sending the form information to the create
method in the ideas_controller.rb
.Idea
.Interacts with the view
@ideas
defined in the index
method of ideas_controller.rb
can be used in the view file, index.html.erb
To recap, the Model, View, and Controller each has its own different responsibilities, but work together inside the application. The main benefit of the MVC framework is that since everything has different responsibilities, each component can work independently.
In software engineering, writing code that isn't dependent on other code is an important concept. When we have code that is dependent on another piece of code, then breaking one piece of the code could cause another part of the application to break. Software engineers call code that is independent and reusable "modular code". When engineers talk about "modularity", or keeping the code "modular", they are talking about how code shouldn't be dependent on another piece of code so that it can be reused in other parts of the program.
The purpose of the MVC framework is to keep each component seperate and reusable.