0
Posted October 13, 2012 by Spyros in Ruby on Rails
 
 

What is The Model View Controller (MVC) Rails Pattern And How it Works

350px-ModelViewControllerDiagram2-300x137
350px-ModelViewControllerDiagram2-300x137

You may have already heard that Rails is based on the Model View Controller design pattern. The MVC pattern is a generally well known design pattern that is frequently met in frameworks, as well as many large scale objects, as game engines. Even if you program a website in PHP, designing your code in an MVC style can make your programming a lot more comprehensive and robust.

To examine the MVC model that Rails is using, please take a look at this very nice representation :

 

As always, the first thing that is happening is that a client connects to a web server. Thus, a browser is (most times) needed. Once the request reaches the web server, it is forwarded to our rails application. And the magic begins. The Rails Routing system (that we are going to talk about in detail in the next posts of this blog), determines which controller is responsible for handling this particular request.

Once this is determined, the action that was asked to be executed from the controller, is executed. The controller is the entity that begins handling the request. A controller cooperates with various models, in order to execute the real logic behind handling data. Imagine that we want to code the routine that creates a new user for our application. The controller(say we name it users), will have an action(say new), that is going to be responsible for handling a new user registration.

Now, the controller is not the actual entity that adds a user to our database. Instead, it receives the requests and directly speaks to the User model. The User model is a database table (named users), that is in fact the one behind the actual registration. In simplistic ruby like pseudo code, the controller would be something like :


action new

  User.add(:name => 'new_user')

end

The action new of our controller just got the request. When we specify User.add, we talk to the model. The model has the add method, which actually adds a new entry to our database. Therefore, a controller should just have a few code that handles things, while the actual logic should be inside the models. Fat models, thin controllers, Rails dictates.

The views are simply HTML code or other client side code(like javascript). At least, they are translated to that. It is what the end user views in his browser. In correct MVC implementation, a view should just talk to the controller and actually present whatever the controller prepares. Utilizing model code inside views, is avoidable and considered quite a bad practice.


Spyros