Slide 1

Slide 1 text

Nola On Rails Session 7 The Controller

Slide 2

Slide 2 text

Retrospective ● We talked about the database ○ What it is ○ What it does ○ Why we need it ● We talked about ODMs ○ That they handle the database ○ They give us Models ○ They can be large or small ● We talked about Models ○ How they are concepts inside your database ○ That they define the concept, both in function and behavior ● We briefly used rails console

Slide 3

Slide 3 text

The Overview of MVC ● Rails is a MVC framework, like many others ● MVC is an acronym that stands for: ○ Model ○ View ○ Controller ● The controller is an important part of a large application ● It determines how to interact with all of your resources ● It handles the response to all requests

Slide 4

Slide 4 text

Creating A Controller ● To get details on creating a controller run rails generate controller ● If you want Rails to do more than that use rails generate scaffold_controller ● We'll make a blank controller using rails generate controller pages ● And a scaffolded controller for our stories rails generate scaffold_controller story

Slide 5

Slide 5 text

The Controller Anatomy ● Controllers will be inside app/controllers/ ● Each controller file contains a Ruby class ● This Ruby class inherits from ApplicationController ● The class contains a series of methods which are actually controller actions

Slide 6

Slide 6 text

ApplicationController ● The ApplicationController is like the father of all controllers ● It's located at app/controllers/application_contr oler.rb ● Things, like actions or methods, defined here will be accessible to other controllers ● Add this line to the class: APP_NAME = "Fantastory" ● We've defined a Constant, the other controllers will have this variable too

Slide 7

Slide 7 text

A Peek Into Actions ● Back in our PagesController add a method called splash ● In the definition of that method write: render text: APP_NAME + " - It's so cool!" ● The render method tells the controller what to respond with ● We're combining the APP_NAME value ("Fantastory") with this other text

Slide 8

Slide 8 text

Routes ● A route is traditionally defined as a path from A to B ● Rails routes are the defined paths to resources of an application ● A route generally is comprised of: ○ A resource /accounts/ ○ An id /accounts/5 ○ An action on the member /accounts/5/edit ○ These are not hard fast rules ● The Routes are defined in config/routes.rb

Slide 9

Slide 9 text

Setting Up Your Routes ● Open the routes folder ● You should see a lot of documentation ● We're going to add a custom route and a root route ● The first route will be pointing to our new PagesController action splash ● Write: get "/splash", controller: : pages, action: :splash ● Now start your database, server, and open your browser to http://localhost:3000/splash ● Now write: root to: "pages#splash"

Slide 10

Slide 10 text

Resources ● http://guides.rubyonrails.org/routing.html