Skip to content

Model View Controller

Alberto Blázquez edited this page Nov 5, 2013 · 1 revision

How to create a new Resource

With Ruby on Rails, it is quite easy to add new domain elements in our application. For example, let's go to imagine we would like to create a new model called User, within its Controller and Views. We only need to type the next command in the terminal:

rails generate scaffold User nick:string password:string age:integer

Understanding Rails

Then, Rails will create 2 new files in the app/ folder, which will be:

  • app/models/User.rb
  • app/controllers/UsersController.rb

as well as several new ".html.erb" files in the app/views/users/ folder such as:

  • index display the list of users
  • show display just the current user selected
  • _form display the form used for creating or editing users, sending a POST / PUT request
  • new calls the form template
  • edit calls the form template

Finally, the file config/routes.rb will be updated too, adding the new "User" resource and allowing the access and use to its natural RESTful URLs.

Relevant Issues

Also, there are two important issues to take into account:

  1. If we are working with a local database, as it is expected by default, Rails will generate a new migration file in db/migrations, so the file db/schema.db will be updated with the new entity in the database and the user should type the command rake db:migrate

  2. Rails will generate automatically the corresponding testing files, but in the spec/ folder, all of them ending with the _spec suffix at the end of the file name. If, for any reason, the developer is not interested in creating these files, you can append this parameter to the command described before: --no-test-framework

How MVC actually works

This picture tries to summarize the communication between these layers in the application:

How Rails and MVC work together

  1. A user is willing to list the users of the app, so he clicks on a link to /users
  2. The Rrouter knows that GET /users should be bound with the index UsersController's index method
  3. In the index method, the controller calls the model using the User.all method
  4. The User Model, under the hood, fetch the data from the database (or consumes an external RESTful API as we are doing in our project using the Her gem instead of ActiveResource)
  5. UsersController stores the data retrieved in the @users attribute
  6. Then, it passes the attribute as a parameter to the corresponding view, which is index.html.erb
  7. The View loops over the collection of users, renders the final HTML and returns it to the controller
  8. Finally, the HTML code is delivered and the user is able to see the users found