The Request Cycle And Rails Architecture
- Request Cycle
- Model View Controller (MVC) Architecture
In this step we'll learn about how the files created by scaffold work together. By the end of this step you should understand the following concepts:
Discussion: What is this diagram?
Talk through this diagram of the request cycle!
Model View Controller (MVC) Architecture
Rails implements a very specific notion of the Model/View/Controller pattern, which guides how you structure your web applications.
- When you visit any page in your application, that request will be handled by a method in a Controller.
- Controllers use the Models to create, read, update, and delete data from the database.
- Controllers pass Ruby objects to the Views.
Let's take a look at the Controller file in suggestotron:
You'll see a method (a line beginning with
def) for each of the views listed above (except _form.html.erb).
- The Model is a bridge between the database and your application's code.
- For all the Models we create in RailsBridge, Model objects have a corresponding record in the database. The name of the table in the database is the plural version of the Model's class name.
Let's take a look at the Topic Model in suggestotron:
- The View generates the HTML that will be displayed in the browser.
- View files are written in ERB, a templating language. It contains HTML with Ruby code embedded in it. The ruby variables in the view stand as placeholders for content that will be filled in when a user requests the page.
Let's take a look at the Topic View files in suggestotron and match each View file with the corresponding page in the browser.
app/views/topics/index.html.erbin your text editor (Sublime):
Creates this page in your web browser:
Match the rest of the Topic View files (in your text editor, Sublime) to a page in your web browser:
You may have noticed that the page for new topics and the page to edit topics looked similar. That's because they both use the code from this file to show a form. This file is called a partial since it only contains code for rendering part of a page. Partials are easy to spot as the filename always starts with an underscore character. They are great for organizing page rendering code into smaller, manageable parts.
Challenge question: Can you find the line of code in
edit.html.erbthat makes the form partial appear?