Other Pages

rails_architecture.step

  img(src: "img/mvc.png", alt: "MVC")

goals {

  goal "Understand the architecture of a Rails app"

  message "In this step we'll learn a bit about Rails architecture. By the end of this step you should understand the following concepts:"

  ul {
    li "Table"
    li "Model"
    li "View"
    li "Controller"
  }
}

explanation {

  h2 "Rails architecture and its relation to the database"


  message "Rails implements a very specific notion of the **Model/View/Controller** pattern, which guides how you structure your web applications."

  h3 "Model"
  message <<-MARKDOWN
* To store the topics  in our rails app, we need  records in the database.
* When we program we handle these topics as Model objects.
* Every Model object has a corresponding record in the database.
* The name of the table in the database is the plural version of the Model's class name. For example, if the Model is called 'Topic', it will automatically query or write to the 'topics' table in the database.
* Rails makes it easy to automatically write records to the database and query the database to get the records again later.
* The Model is a bridge between the database and your application's code.
  MARKDOWN

  h3 "View"
  message <<-MARKDOWN
* 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.
* To get data into the view we set variables in the controller that are available in the view.
  MARKDOWN

  h3 "Controller"
  message <<-MARKDOWN
* When you visit any page in your application, that request will be handled by a method in a Controller.
* Controllers handle Ruby objects, for example the topic controller might read Topic objects from the database.
* Each method in the controller finishes it's work by calling a view.
  MARKDOWN

  message <<-MARKDOWN
When Models, Views and Controllers are all put together, they follow a pattern: Given a URL, Rails will look up which Controller method (also called an "Action") to use. The Controller Action will use methods in a corresponding Model. The Model will need to read or write to the database, and return an object containing that data to the Controller. The Controller will take that object and pass it to the View. (Actions normally have a corresponding View file, and Rails will automatically find and use that file.)

Models, Views and Controllers each have specific jobs.  Separating responsibilities like this make it easier to develop, especially as it gets bigger. (When each file has a clear responsibility it's easier to fix problems and add new features.)
  MARKDOWN

  message <<-MARKDOWN
  If you want to learn more about Rails Architecture, you may want to watch this video explanation (3 min 30 sec) [MVC architecture *Youtube*](https://www.youtube.com/watch?v=eTdVkgF_Slo)
  MARKDOWN
}

next_step "CRUD_with_scaffolding"