table of contents€¦ · ruby on rails 3 ©2013 /training/etc inc. reproduction of these materials...

55
RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What is Ruby on Rails? ................................................................................ 1-2 Overview of Rails Components..................................................................... 1-3 Installing Rails............................................................................................... 1-5 A Simple Rails Application ............................................................................ 1-6 Starting the Rails Server ............................................................................... 1-8 Static Pages Within a Rails Application ...................................................... 1-10 The Structure of a Rails Application............................................................ 1-11 Generating a Controller .............................................................................. 1-12 Rendering the View .................................................................................... 1-15 Adding a Static Page .................................................................................. 1-17 Dynamic Pages with Embedded Ruby........................................................ 1-20 Using the render Method .......................................................................... 1-26 Using the link_to Method........................................................................ 1-27 CHAPTER 2: RAILS AND HTML FORMS A Basic HTML Form ..................................................................................... 2-2 Processing an HTML Form ........................................................................... 2-5 Working With Form Data............................................................................... 2-6 Other Form Elements ................................................................................. 2-11 Form Tag Helpers ....................................................................................... 2-16 CHAPTER 3: DATABASES AND RAILS Review of the MVC Architecture ................................................................... 3-2 Entities and Relationships ............................................................................ 3-3 Databases and Models ................................................................................. 3-5 Rails Database Conventions......................................................................... 3-7 Adding a Model ............................................................................................. 3-9 Database Migrations ................................................................................... 3-11 The Rails Console ...................................................................................... 3-14 The Rails Database Console ...................................................................... 3-15 Creating a Rails View of a Database Table ................................................ 3-16 Scaffolding .................................................................................................. 3-21 RESTful Routes and Resources ................................................................. 3-24 CHAPTER 4: FORM HELPERS AND VALIDATION Introduction ................................................................................................... 4-2 Form Helpers and form_for ....................................................................... 4-3 Processing Form Helpers ............................................................................. 4-7 From Form to Database................................................................................ 4-9 Redirection.................................................................................................. 4-12 Data Validation ........................................................................................... 4-13 Validation Helpers....................................................................................... 4-14 The presence Validator ............................................................................ 4-15 The numericality Validator.................................................................... 4-16 EVALUATION COPY

Upload: others

Post on 19-Jul-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v

Table of Contents

CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What is Ruby on Rails? ................................................................................ 1-2 Overview of Rails Components..................................................................... 1-3 Installing Rails............................................................................................... 1-5 A Simple Rails Application............................................................................ 1-6 Starting the Rails Server............................................................................... 1-8 Static Pages Within a Rails Application ...................................................... 1-10 The Structure of a Rails Application............................................................ 1-11 Generating a Controller .............................................................................. 1-12 Rendering the View .................................................................................... 1-15 Adding a Static Page .................................................................................. 1-17 Dynamic Pages with Embedded Ruby........................................................ 1-20 Using the render Method.......................................................................... 1-26 Using the link_to Method........................................................................ 1-27

CHAPTER 2: RAILS AND HTML FORMS A Basic HTML Form ..................................................................................... 2-2 Processing an HTML Form........................................................................... 2-5 Working With Form Data............................................................................... 2-6 Other Form Elements ................................................................................. 2-11 Form Tag Helpers....................................................................................... 2-16

CHAPTER 3: DATABASES AND RAILS Review of the MVC Architecture ................................................................... 3-2 Entities and Relationships ............................................................................ 3-3 Databases and Models ................................................................................. 3-5 Rails Database Conventions......................................................................... 3-7 Adding a Model............................................................................................. 3-9 Database Migrations................................................................................... 3-11 The Rails Console ...................................................................................... 3-14 The Rails Database Console ...................................................................... 3-15 Creating a Rails View of a Database Table ................................................ 3-16 Scaffolding.................................................................................................. 3-21 RESTful Routes and Resources................................................................. 3-24

CHAPTER 4: FORM HELPERS AND VALIDATION Introduction................................................................................................... 4-2 Form Helpers and form_for ....................................................................... 4-3 Processing Form Helpers ............................................................................. 4-7 From Form to Database................................................................................ 4-9 Redirection.................................................................................................. 4-12 Data Validation ........................................................................................... 4-13 Validation Helpers....................................................................................... 4-14 The presence Validator ............................................................................ 4-15 The numericality Validator.................................................................... 4-16

EVALUATION COPY

Page 2: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. vi

The uniqueness Validator........................................................................ 4-17 The length Validator ................................................................................ 4-18 The format Validator ................................................................................ 4-20 Custom Validation Methods........................................................................ 4-21 The errors Object .................................................................................... 4-23 Displaying Validation Errors in the View ..................................................... 4-24

CHAPTER 5: ADDING STYLE TO AN APPLICATION Styling........................................................................................................... 5-2 Rails and Sass.............................................................................................. 5-4 Cascading Style Sheets................................................................................ 5-5

CHAPTER 6: USERS Introduction................................................................................................... 6-2 Configuring an Application for Sessions ....................................................... 6-3 Registering Users ......................................................................................... 6-5 The Register Action .................................................................................... 6-10 The flash Hash ........................................................................................ 6-12 Validating the Registration.......................................................................... 6-16 Logging in ................................................................................................... 6-17 Logging Out ................................................................................................ 6-21 Protected Pages ......................................................................................... 6-22 Filters.......................................................................................................... 6-23

CHAPTER 7: PUTTING IT ALL TOGETHER Introduction................................................................................................... 7-2 The Business Application ............................................................................. 7-3 Database Terminology.................................................................................. 7-9 Linking Two Models .................................................................................... 7-11 Adding Tasks.............................................................................................. 7-12 The Database Tables ................................................................................. 7-16 Displaying Employee Tasks........................................................................ 7-17 Deleting a Task........................................................................................... 7-20 Listing Employees and Tasks ..................................................................... 7-21 Migrations ................................................................................................... 7-23 Editing a Record ......................................................................................... 7-28 Summary .................................................................................................... 7-32

EVALUATION COPY

Page 3: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-1

Chapter 1: An Overview Of Ruby on Rails

1) What is Ruby on Rails? ........................................................................................... 1-2

2) Overview of Rails Components............................................................................... 1-3

3) Installing Rails.......................................................................................................... 1-5

4) A Simple Rails Application ..................................................................................... 1-6

5) Starting the Rails Server ......................................................................................... 1-8

6) Static Pages Within a Rails Application .............................................................. 1-10

7) The Structure of a Rails Application ................................................................... 1-11

8) Generating a Controller ........................................................................................ 1-12

9) Rendering the View................................................................................................ 1-15

10) Adding a Static Page.............................................................................................. 1-17

11) Dynamic Pages with Embedded Ruby ................................................................. 1-20

12) Using the render Method.................................................................................... 1-26

13) Using the link_to Method ................................................................................. 1-27

EVALUATION COPY

Page 4: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-2

What is Ruby on Rails?

• Ruby on Rails, often shortened to Rails or RoR, is a database-backed web application development framework written in the Ruby language.

First released in 2004, it aims to increase the speed and ease of web application development.

The ease of development stems from assumptions made by the creators of the framework as to what is needed by developers to get started.

• Ruby on Rails assumes there is a best way to do things and is designed that way, while often discouraging alternative designs.

• The Rails philosophy is built around the following guiding principles.

DRY - Don't Repeat Yourself.

• Repetition of code and/or information is a bad thing. Convention Over Configuration

• The Rails framework makes assumptions about what needs to be done and the best way to accomplish it.

• This is in stark contrast to the use of configuration files in other frameworks that require one to specify every little detail.

REST - Representational State Transfer

• REST uses these existing features of the HTTP protocol to organize applications and the resources they use.

MVC - Model, View, Controller Architecture

• MVC isolates the business logic from the user interface and assists in the maintenance of the code by clearly defining where different types of code belong within the application.

EVALUATION COPY

Page 5: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-3

Overview of Rails Components

• The Rails framework is composed of the following individual components.

Action Pack Active Model

• Action Controller Active Record

• Action View Active Resource

• Action Dispatch Active Support

Action Mailer Railties

• An overview of each of the above components is provided below.

Action Pack

• This gem provides the Action Controller, Action Dispatch, and Action View components to the framework.

• These components provide the View and Controller parts of MVC.

Action Controller

• This component processes incoming requests to a rails application and dispatches to an intended action.

Action View

• Action View manages the HTML and/or XML views that are the default output of the application through the use of view templates.

Action Dispatch

• This handles the routing of web requests and dispatches them to the application.

EVALUATION COPY

Page 6: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-4

Overview of Rails Components Action Mailer

• This provides a framework for including email services within an application.

Active Model

• This component provides an interface between the View and Controller components of the Action Pack services and Active Record (described below).

• It allows other Object Relationship Mapping (ORM) frameworks in place of Active Record if desired.

Active Record

• This provides the base for the Model part of MVC within a Rails application.

Active Resource

• Active Resource provides a framework for managing connections between business objects and RESTful services within the application.

Active Support

• This is a collection of utility classes and used within the core Rails code and your applications.

Railties

• Railties is the core Rails code that builds the Rails applications and connects the frameworks and plugins used within a Rails application.

EVALUATION COPY

Page 7: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-5

Installing Rails

• When Ruby is installed, there are additional tools included within the installation.

One such tool is the gem application, which is an interface to the RubyGems package system.

• RubyGems is a system for managing Ruby software libraries.

• Ruby code packaged in this manner is called a gem.

• With RubyGems, you can install the latest version of Rails and its dependencies through the following command line.

gem install rails

Note that the above command may require 'root' access in a Linux environment.

The following command will show the version of Rails that is installed on the machine.

rails -v

• The machines in the classroom have had a specific version of Rails installed by specifying the version to install using a command similar to the one shown below. gem install rails -v 3.2.13

• Since Rails 3.1, a JavaScript runtime has been needed for development on Linux.

It is not needed for Mac OS X or Windows.

• Node.js has already been installed and added to the PATH environment variable for this course.

EVALUATION COPY

Page 8: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-6

A Simple Rails Application

• The first application we will build in Rails will be a simple one.

Almost all Rails applications are started the same way, through the use of the rails command.

The rails program creates a skeleton application to get you started.

• We will start by creating a directory to place all of the Rails applications that we will be developing.

The directory should be created in the user's home directory and named railsapps.

$ mkdir railsapps

Once the directory is created, we will change into that directory.

$ cd railsapps

• Note that throughout the course, we will show the Linux shell/command prompt ($), although we could have shown the Windows (>) prompt just the same.

• From within the railsapps directory, we will enter the following command.

$ rails new firstapp

In a Linux environment you may be prompted to enter the user's password (assuming they are in the sudoers list).

The above command creates a new Rails application called firstapp in a directory of the same name.

EVALUATION COPY

Page 9: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-7

A Simple Rails Application

• There will be a lot of output displaying the name of each file or directory being created to support the application being built called Firstapp - located in a directory named firstapp.

• Below is a summary of the purpose of each of the files and folders that are created by default.

File/Folder Purpose app/ Contains the models, views, controllers and assets config/ Configuration rules for runtime, routes, database, and more config.ru Rack configuration for Rack based middleware db/ Contains database schema and database migrations doc/ Documentation for the application Gemfile Pertains to gem dependencies needed by application Gemfile.lock Pertains to gem dependencies needed by application lib/ Extended modules for application log/ Application log files public/ Static files and compiled assets accessible to the public Rakefile Default Rake tasks README.rdoc Instruction manual for your app script/ Rails script(s) that are used to deploy and run application test/ Unit tests, fixtures, and other test apparatus tmp/ Temporary files vendor/ Third party code .gitignore Patterns for files to be ignored by Git

A more in depth understanding of the files and directories listed above, as well as their purpose, will be gained as the course progresses.

• With an application created, we will now demonstrate how to start up the Rails server in order to access the application.

EVALUATION COPY

Page 10: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-8

Starting the Rails Server

• The previous pages demonstrated how to create a new Rails application by passing the new command to the rails executable.

Running just the rails executable without any command will list all of the rails commands that are available.

student@localhost:~/railsapps/firstapp $ rails Usage: rails COMMAND [ARGS] The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") dbconsole Start a console for the database specified in config/database.yml (short-cut alias: "db") new Create a new Rails application. "rails new my_app" creates a new application called MyApp in "./my_app" In addition to those, there are: application Generate the Rails application code destroy Undo code generated with "generate" (short-cut alias: "d") benchmarker See how fast a piece of code runs profiler Get profile information from a piece of code plugin Install a plugin runner Run a piece of code in the application environment (short-cut alias: "r") All commands can be run with -h (or --help) for more information. $

• We will start the Rails server by passing the rails executable the server or s command.

student@localhost:~/railsapps/firstapp $ rails s => Booting WEBrick => Rails 3.2.13 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2013-03-29 12:15:58] INFO WEBrick 1.3.1 [2013-03-29 12:15:58] INFO ruby 1.9.3 (2013-02-22) [i686-linux] [2013-03-29 12:15:58] INFO WEBrick::HTTPServer#start: pid=2096 port=3000

The WEBrick server that is launched comes prepackaged with the installation of Ruby.

• Alternative servers such as Mongrel or Apache could also be configured to work with Rails, if desired.

EVALUATION COPY

Page 11: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-9

Starting the Rails Server

• In order to ensure that the server is up and running, we can access it via a web browser using the following URL.

http://localhost:3000

Note that by default, the WEBrick server listens for connections on port 3000 rather than the standard HTTP port 80.

Information pertaining to each request sent to the server can be seen in the server console as shown below.

student@localhost:~/railsapps/firstapp $ rails s => Booting WEBrick => Rails 3.2.13 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2013-03-29 12:15:58] INFO WEBrick 1.3.1 [2013-03-29 12:15:58] INFO ruby 1.9.3 (2013-02-22) [i686-linux] [2013-03-29 12:15:58] INFO WEBrick::HTTPServer#start: pid=2096 port=3000 Started GET "/assets/rails.png" for 127.0.0.1 at 2013-03-29 12:17:33 -0400 Served asset /rails.png - 200 OK (7ms)

EVALUATION COPY

Page 12: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-10

Static Pages Within a Rails Application

• Recall that each Rails application created generates a skeleton working application.

The directory structure of this application, as shown earlier, contains a directory named public.

• Rails serves any files within the public directory directly to the browser.

• Part of the skeleton application created is a special file within the public directory, named index.html.

By convention, it acts as the home page for the application.

It is special in that its use in the URL is optional.

• The following two URLs will present the same web page. http://localhost:3000/ http://localhost:3000/index.html

• The HTML file shown below can be created within the public directory of the application and accessed at the URL of: http://localhost:3000/hello.html

hello.html

1. <html> 2. <head><title>Hello World</title></head> 3. <body><h1>A Sample HTML Page</h1></body> 4. </html>

Note that this can be done without restarting the server.

• By convention, the WEBrick server starts up in development mode, which does not require a restart when an application is modified.

EVALUATION COPY

Page 13: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-11

The Structure of a Rails Application

• While the ability of a Rails application to return static HTML files exists, dynamically generated responses are typically a core part of any Rails application.

• The next directory (within a skeleton Rails application) that we will study is the app directory.

Directly related to the app directory is the Model-View-Controller (MVC) pattern that Rails follows.

• Rails, through the use of MVC, enforces the separation between the domain or business logic from the input and presentation logic.

• Within a dynamic web application, a controller typically takes an incoming request, interacts with a model, and then renders the view as the response back to the browser.

The three directories within the app directory pertaining directly to the MVC architecture are listed below.

• controllers

• models

• views

• Since the controller typically interacts with both the view and the model within the MVC architecture, it will be the first piece that we build into our application.

The controller used by Rails is the ActionController class.

• An ActionController is made up of one or more actions (methods in the class).

• A file named routes.rb is used to link the actions of an ActionController to URLs.

EVALUATION COPY

Page 14: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-12

Generating a Controller

• Rails includes a script, named generate, for generating various types of Rails components.

Passing the first argument of controller to the generate script can be used to generate Rails controllers.

• The only other required argument is the name of the controller to be created.

• Optionally, additional arguments can be passed representing the actions that are to be created.

• We will generate a controller named StaticPages with two actions named home and guestbook.

This will be done using the following command.

rails generate controller StaticPages home guestbook

The results can be seen below.

student@localhost:~/railsapps/firstapp $ rails generate controller StaticPages home guestbook create app/controllers/static_pages_controller.rb route get "static_pages/guestbook" route get "static_pages/home" invoke erb create app/views/static_pages create app/views/static_pages/home.html.erb create app/views/static_pages/guestbook.html.erb invoke test_unit create test/functional/static_pages_controller_test.rb invoke helper create app/helpers/static_pages_helper.rb invoke test_unit create test/unit/helpers/static_pages_helper_test.rb invoke assets invoke coffee create app/assets/javascripts/static_pages.js.coffee invoke scss create app/assets/stylesheets/static_pages.css.scss $

• In addition to the list of files created above, the generating of the controller updates the routes file named routes.rb.

• The routes.rb file is located in the config directory of the application.

EVALUATION COPY

Page 15: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-13

Generating a Controller

• As shown in the routes.rb file below, each action generated results in a rule being added to the routes file.

routes.rb

1. Firstapp::Application.routes.draw do 2. get "static_pages/home" 3. 4. get "static_pages/guestbook" 5. 6. # The priority is based upon order of creation: 7. . 8. . 9. . 10. end

The get "static_pages/home" rule above maps requests for the URL of /static_pages/home to the home action in the StaticPagesController class.

• The get at the beginning of the rule indicates that the action responds to a HTTP GET request.

• Navigating to the mapped URL of /static_pages/home results in the following page being displayed.

• A similar page is available for the following URL.

/static_pages/guestbook

EVALUATION COPY

Page 16: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-14

Generating the Controller

• Before looking at the generated HTML pages, we will look at the StaticPagesController class that was generated earlier via the following command.

rails generate controller StaticPages home guestbook

The controller can be found at the following location within the application directory.

app/controllers/static_pages_controller.rb static_pages_controller.rb

1. class StaticPagesController < ApplicationController 2. def home 3. end 4. 5. def guestbook 6. end 7. end

The ApplicationController class, from which StaticPagesController inherits, is defined in another generated file in the same directory named application_controller.rb

application_controller.rb

1. class ApplicationController < ActionController::Base 2. protect_from_forgery 3. end

• The default behavior for all action controllers is typically

declared in the ApplicationController class that all action controllers inherit from.

• The home and guestbook actions generated when the StaticPagesController was generated are initially empty.

EVALUATION COPY

Page 17: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-15

Rendering the View

• Recall that many files were created with the following command.

rails generate controller StaticPages home guestbook

So far, we have looked at the following generated files.

• app/config/routes.rb

• app/controllers/static_pages_controller.rb

• app/controllers/application_controller.rb

• When actions are supplied to the rails generate controller script, such as the home and guestbook actions above, the script also creates a view (the View part of MVC) for each action.

The views created for the home and guestbook actions are:

• app/views/static_pages/home.html.erb

• app/views/static_pages/guestbook.html.erb

The .erb (embedded Ruby) extension indicates that the file may contain embedded Ruby code.

The .html in the file name indicates that the file contains HTML.

• The generated .html.erb files listed above do not yet have any embedded Ruby code in them. They are simply snippets of HTML code that can be seen on the following page.

EVALUATION COPY

Page 18: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-16

Rendering the View home.html.erb

1. <h1>StaticPages#home</h1> 2. <p>Find me in

app/views/static_pages/home.html.erb</p>

guestbook.html.erb

1. <h1>StaticPages#guestbook</h1> 2. <p>Find me in

app/views/static_pages/guestbook.html.erb</p>

• The actual view rendered to the user for each action is created by combining the code in the above views into another file that controls the overall layout of both of the views.

The name of the file, acting as a template for the layout of the actions' views, can be found at the following location.

• app/views/layouts/application.html.erb application.html.erb

1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>Firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <%= yield %> 12. </body> 13. </html>

The embedded Ruby is all of the code above between the <%= %> tags and will be discussed in more detail shortly.

EVALUATION COPY

Page 19: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-17

Adding a Static Page

• The previous pages have concentrated on many of the files that are automatically generated by the generate controller command.

We will now concentrate on how to manually add an additional page to the existing application named Firstapp.

The page we will create will be associated with an action named info.

• We will model this around the structure that was created for the previous home and guestbook actions.

• Adhering to the standard Rails naming conventions will be an important part in the new additions working properly.

Accomplishing this requires a minimum of three things.

• Add a route to the routes file for the action. • Add the action to the StaticPagesController. • Create a corresponding view for the action.

• The first step to creating the new page is to update the routes.rb file, as shown below.

routes.rb

1. Firstapp::Application.routes.draw do 2. get "static_pages/home" 3. get "static_pages/guestbook" 4. 5. get "static_pages/info" 6. . 7. . 8. . 9. end

The line above, in bold, maps the URL of static_pages/info to the info action in the controller.

EVALUATION COPY

Page 20: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-18

Adding a Static Page

• Attempting to access the newly mapped URL will result in the following page being displayed.

The above indicates that the action (method) named info has not been defined yet inside of the controller.

• The second step is to add the missing info action to the controller as shown below.

static_pages_controller.rb

1. class StaticPagesController < ApplicationController 2. def home 3. end 4. 5. def guestbook 6. end 7. 8. def info 9. end 10. end

Attempting to access the URL will now result in a different error being displayed, as shown on the next page.

EVALUATION COPY

Page 21: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-19

Adding a Static Page

• The last step to creating a new static page will be to define the view (template) to avoid the above error.

The name of the file that needs to be created, in order to act as the view, will be info.html.erb. It is shown below.

info.html.erb

1. <h1>StaticPages#info</h1> 2. Find me in: 3. <code>app/views/static_pages/info.html.erb</code> 4. <p>Feel free to add any other 5. information to this page</p>

• The view that that the controller will present is displayed

below.

EVALUATION COPY

Page 22: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-20

Dynamic Pages with Embedded Ruby

• The Firstapp application that has been created consists of the three actions with the following three views.

app/views/static_pages/guestbook.html.erb

app/views/static_pages/home.html.erb

app/views/static_pages/info.html.erb

• While the above views are permitted to have embedded Ruby in them, they currently contain only static HTML.

Recall that all of the views rely on the following template for the layout of each view.

• app/views/layouts/application.html.erb application.html.erb

1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>Firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <%= yield %> 12. </body> 13. </html>

• This file contains special tags where the Ruby code inside of them results in dynamic output generated in the view.

The purpose of the template is to rely on the DRY principle mentioned earlier where you Don't Repeat Yourself.

EVALUATION COPY

Page 23: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-21

Dynamic Pages with Embedded Ruby

• Most, if not all, browsers provide a way of viewing the page source that the browser receives to render the view.

Below is the result of viewing the source of the info view through the browser.

Each set of <%= => tags within application.html.erb results in dynamic output that is sent to the browser.

• For instance the following tag: <%= javascript_include_tag "application" %>

results in the following script tags being sent to the browser. <script src="/assets/jquery.js?body=1" ... <script src="/assets/jquery_ujs.js?body=1" ... <script src="/assets/static_pages.js?body=1" ... <script src="/assets/application.js?body=1" ...

EVALUATION COPY

Page 24: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-22

Dynamic Pages with Embedded Ruby

• For each of the views, anything that is similar to all of them can be placed within the application.html.erb file.

The parts of the view that are specific to each are then placed in their respective .erb files.

• When working with embedded Ruby, two special tags can be used to surround the Ruby code that will then be executed to generate dynamic content.

<%= %>

• This is typically referred to as output embedding tags. • Use of this tag results in the Ruby expression inside of the

tag being evaluated and inserted into the HTML stream.

<% %>

• This is typically referred to as regular embedding tags. • Use of this tag will evaluate all of the Ruby code inside of the

tag but nothing is inserted into the HTML stream.

• We will modify the info view to include several of the embedded Ruby tags to include some dynamic output.

The changes will be as follows.

• Use regular embedding tags to initialize some variables. • Use output embedding tags to output the variables. • Use output embedding tags to output a Ruby object.

The modified info view is shown on the next page.

EVALUATION COPY

Page 25: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-23

Dynamic Pages with Embedded Ruby info.html.erb

1. <h1>StaticPages#info</h1> 2. Find me in: 3. <code>app/views/static_pages/info.html.erb</code> 4. <% x = 10 5. y = 20 6. z = x + y 7. lucky_number = rand(100) 8. %> 9. <div>x = <%= x %></div> 10. <div>y = <%= y %></div> 11. <div>x + y = <%= z %></div> 12. <hr /> 13. <div>Your lucky number is: 14. <%= lucky_number %></div> 15. <hr /> 16. Today is: <%=Time.now.to_s %><br /> 17. Today is: <%=Time.now %><br />

The updated info view looks like the following in the browser.

• Refreshing the page should produce different values since the page is being generated dynamically.

EVALUATION COPY

Page 26: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-24

Dynamic Pages with Embedded Ruby

• All three views currently have an <h1> tag defined at the top whose data is similar to all three views.

The technique we will use to get rid of the repetitiveness between the pages will involve creating Ruby instance variables within the actions of the controller.

• Since the variable part of the <h1> tag is the name of the view, we will set the value of an instance variable we will call @view_name to the appropriate value for each action.

• This @view_name instance variable can then be accessed within the embedded Ruby tag to output its value.

• The end result will be an <h1> tag identical within all three views. Therefore we will instead move it to the layout file that is common to all three views.

The modified version of the controller is shown below where the code that has been added is shown in bold.

static_pages_controller.rb

1. class StaticPagesController < ApplicationController 2. def home 3. @view_name = "home" 4. end 5. 6. def guestbook 7. @view_name = "guestbook" 8. end 9. 10. def info 11. @view_name = "info" 12. end 13. end

With the @view_name instance variable defined, the modified layout file that will use the variable in an embedded ruby tag is shown on the next page.

EVALUATION COPY

Page 27: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-25

Dynamic Pages with Embedded Ruby application.html.erb

1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title>Firstapp</title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <h1>StaticPages#<%= @view_name %></h1> 12. <%= yield %> 13. 14. </body> 15. </html>

Since the <h1> tag and its dynamic content is now defined within the template, the corresponding <h1> tag in each of the views can now be removed.

• This can be seen in the modified home.html.erb view shown below.

home.html.erb

1. <p>Find me in app/views/static_pages/home.html.erb</p>

EVALUATION COPY

Page 28: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-26

Using the render Method

• The default behavior of each of the actions defined in a controller is to render a view whose name corresponds to that of the action.

i.e., the info action rendering the info.html.erb view.

• The render method of the controller, inherited from ActionController::Base, can be used to render a view that is associated with a different action, if desired.

There are three variations on the Ruby syntax that can be used to accomplish this inside one of your actions.

In the variations below, name_of_an_action should be replaced with the actual name of an action such as info, guestbook, or home in the current application.

• The first variation passes a string to the render method. render "name_of_an_action"

• The second variation passes a symbol.

render :name_of_an_action

• The last variation passes a hash to the render method. This is from Rails 2 but is no longer required in Rails 3. render :action => "name_of_an_action"

So, if the info method were to be defined as follows:

def info render :guestbook end

• The info action would render the guestbook.html.erb

view rather than the default of info.html.erb.

EVALUATION COPY

Page 29: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-27

Using the link_to Method

• The link_to method allows easy navigation to URLs.

The URLs generated by the method may be to views within the application or URLs outside of the application.

The link_to method takes a variable number of arguments (and as such there are several variations on how the method can be used).

• The first argument should be a string representing the text to display for the link that will be created.

• The second argument is the URL to link to, and can either be a string representing the URL to use, or a literal hash of the action/value pair.

• Subsequent arguments are a hash of attributes and values that are added to the generated link.

• Several examples of using the link_to method within embedded Ruby and the resulting tag that is generated are shown below.

<%= link_to "Info", {:action => "info"} %>

• generates the following link: <a href="/static_pages/info">Info</a>

<%= link_to "Info", "info" %>

• generates the following link: <a href="info">Info</a>

<%= link_to "/training/etc",

"http://trainingetc.com", :class => "links" %>

• generates the following link: <a href="http://trainingetc.com" class="links">/training/etc</a>

EVALUATION COPY

Page 30: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-28

Using the link_to Method

• A modified version of the home view is shown below.

The examples of the link_to method from the previous page and some additional examples have been included.

home.html.erb

1. <p>Find me in 2. app/views/static_pages/home.html.erb</p> 3. <h3>Links passing action name as a hash<h3> 4. <%= link_to "Info", {:action => "info"} %> | 5. <%= link_to "GuestBook", {:action => "guestbook"} %> 6. <hr> 7. <h3>Links passing a relative URL as a string<h3> 8. <%= link_to "Info", "info" %> | 9. <%= link_to "GuestBook", "guestbook" %> 10. <hr> 11. <h3>Link passing an absolute URL as string<h3> 12. <%= link_to "/training/etc", 13. "http://trainingetc.com" %> 14. <%= link_to "/training/etc", 15. "http://trainingetc.com", :class => "links" %>

EVALUATION COPY

Page 31: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 1-29

Exercises 1. You are going to mimic most of the things we have done

in this chapter.

Create a Rails application named Store.

Create a controller named Inventory with index, buy, and sell actions.

• Recall that passing the actions as parameters when the controller is being generated will also create the associated views/templates.

Start the Rails server.

Test each of the following URLs.

• http://localhost:3000

• http://localhost:3000/inventory/index

• http://localhost:3000/inventory/buy

• http://localhost:3000/inventory/sell

Modify the index action to generate a random number between 0 and 99.

• Now, use the render method to render either the buy or sell view, depending upon whether the random number is greater than 50.

• In either case, include the random number within the view.

Now, place a link in both the buy and sell views permitting a user to easily navigate back to the index view.

EVALUATION COPY

Page 32: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-1

Chapter 6: Users

1) Introduction.............................................................................................................. 6-2

2) Configuring an Application for Sessions ............................................................... 6-3

3) Registering Users ..................................................................................................... 6-5

4) The Register Action ............................................................................................... 6-10

5) The flash Hash.................................................................................................... 6-12

6) Validating the Registration ................................................................................... 6-16

7) Logging in ............................................................................................................... 6-17

8) Logging Out............................................................................................................ 6-21

9) Protected Pages ...................................................................................................... 6-22

10) Filters ...................................................................................................................... 6-23

EVALUATION COPY

Page 33: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-2

Introduction

• HTTP is called a stateless protocol because each command is executed independently.

There is no knowledge in an incoming command of the command that came before it.

• This is a often a problem for many web based applications that need to track things likes purchases, users logged into a system, etc.

• This chapter begins by demonstrating how Rails applications can be written to maintain state over multiple HTTP requests.

• Various solutions have been developed to maintain the state of a session using HTTP.

Two of the most common are Cookies and URL rewriting.

By convention, Rails relies on the cookie-based approach.

• A cookie is a piece of named data (think key/value pair).

The cookie is set as a header in the response to the browser.

• Subsequent requests to the server from the browser will result in the browser setting it as a header in the request.

Applications then begin to use the data in the cookie to match against the session information stored on the server.

• Rails utilizes a hash named session that is available to both the controllers and the views of the application.

By convention Rails stores all session data on the client side, but we will configure it to store the session data in a table on the server side.

EVALUATION COPY

Page 34: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-3

Configuring an Application for Sessions

• In order to demonstrate how the session is used within an application and the issues related to it, we will develop a new application that manages users on a site.

We start with a simple User model containing a name, email address, and password.

• We will not worry about encryption of the password in this example, although a real world example would definitely want to incorporate it.

• Below are the usual steps needed to set up the new application.

student@localhost:~/railsapps $ cd ~/railsapps $ rails new Sessions $ cd Sessions $ rails generate controller Admin index login logout register $ rails generate model User loginname:string email:string password:string $ rake db:migrate

Because we intend to be storing the session information in the database, we will also create and migrate a table for it.

student@localhost:~/railsapps $ rake db:sessions:create $ rake db:migrate

EVALUATION COPY

Page 35: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-4

Configuring an Application for Sessions

• The session can use several storage mechanisms.

ActionDispatch::Session::CookieStore

• Stores everything on the client ActiveRecord::SessionStore

• Stores the data in a database using Active Record ActionDispatch::Session::CacheStore

• Stores the data in the Rails cache ActionDispatch::Session::MemCacheStore

• Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead)

• In order to configure Rails to store the sessions in the new table, we will need to edit the following file.

config/initializers/session_store.rb:

We will comment out the line that uses the CookieStore, and uncomment the line that uses the SessionStore.

session_store.rb

1. # Be sure to restart your server when you modify ... 2. 3. #Sessions::Application.config.session_store

:cookie_store, :key => '_Sessions_session' 4. 5. # Use the database for sessions instead of the ... 6. # which shouldn't be used to store highly ... 7. # (create the session table with "rails generate ... 8. Sessions::Application.config.session_store

:active_record_store

EVALUATION COPY

Page 36: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-5

Registering Users

• The registration form for collecting information about a potential user is shown below.

It can be found in the startercode directory for this chapter.

It should be copied to the app/views/admin directory, overwriting the register.html.erb file that was provided.

register.html.erb

1. <h2>Register</h2> 2. <%= form_for :user, 3. :url => { :action => "register" } do |f| %> 4. <%= f.error_messages %> 5. <fieldset><legend>Enter Your Details</legend> 6. <table border="1"> 7. <tr> 8. <td><%= f.label :loginname, "Screen Name" %></td> 9. <td><%= f.text_field :loginname, 10. :size => User::NAME_SIZE, 11. :maxlength => User::NAME_MAX_LENGTH %></td> 12. </tr> 13. <tr> 14. <td><%= f.label :email %></td> 15. <td><%= f.text_field :email, 16. :size => User::EMAIL_SIZE, 17. :maxlength=>User::EMAIL_MAX_LENGTH %></td> 18. </tr> 19. <tr> 20. <td><%= f.label :password %></td> 21. <td><%= f.password_field :password, 22. :size => User::PWD_SIZE, 23. :maxlength=>User::PWD_MAX_LENGTH %></td> 24. </tr> 25. <tr> 26. <td colspan="2" align="center"> 27. <%= f.submit "Register!" %></td> 28. </tr> 29. </table> 30. </fieldset> 31. <% end %>

EVALUATION COPY

Page 37: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-6

Registering Users

• Recall that the following embedded Ruby tag provides information about any validation errors to the view.

<%= f.error_messages %>

Recall that in order to use the above tag in the previous view, it requires a gem be added to the file named Gemfile.

Gemfile

1. source 'https://rubygems.org' 2. 3. gem 'rails', '3.2.1' 4. . 5. . 6. . 7. gem 'sqlite3' 8. gem "dynamic_form" 9. . 10. . 11. .

• Once the Gemfile file has been updated, a bundle

install command will be needed to actually bundle all of the dependent gems.

student@localhost:~/railsapps/Sessions $ cd ~/railsapps/Sessions $ bundle install $

• Several of the form helper methods in the view are referencing constants, as shown in the sample tag below. <%= f.text_field :loginname, :size => User::NAME_SIZE, :maxlength => User::NAME_MAX_LENGTH %>

These constants are defined in the model as shown on the following page.

EVALUATION COPY

Page 38: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-7

Registering Users

• The model for the User objects is shown below.

Since certain values will be used both within the model and within the view from the previous page, they are being declared as constants to make them easily accessible from within the view.

user.rb

1. class User < ActiveRecord::Base 2. attr_accessible :email, :loginname, :password 3. 4. NAME_MIN_LENGTH = 4 5. NAME_MAX_LENGTH = 20 6. PWD_MIN_LENGTH = 4 7. PWD_MAX_LENGTH = 40 8. EMAIL_MAX_LENGTH = 50 9. NAME_RANGE = NAME_MIN_LENGTH..NAME_MAX_LENGTH 10. PWD_RANGE=PWD_MIN_LENGTH..PWD_MAX_LENGTH 11. NAME_SIZE = 20 12. PWD_SIZE = 10 13. EMAIL_SIZE = 30 14. end

The user.rb file shown above can also be found in the startercode directory for this chapter.

• You should copy over and overwrite the existing file located in the app/models directory.

• A stylesheet will also be included to give the entire application a more professional look.

The admin.css.scss stylesheet on the following page can also be found in the startercode directory for the chapter.

• You should copy over and overwrite the existing file located in the app/assets/stylesheets directory.

EVALUATION COPY

Page 39: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-8

Registering Users admin.css.scss

1. body { 2. font-family: sans-serif; 3. margin: 0px; 4. text-align: center; 5. } 6. #flash { 7. color: maroon; 8. font-size: 24pt; 9. } 10. #whole_page { 11. width: 50em; 12. margin: auto; 13. padding: 0px; 14. text-align: left; 15. } 16. #header { 17. color: white; 18. background: maroon; 19. font-size: 24pt; 20. padding: 0.25em; 21. margin-bottom: 0px; 22. } 23. #links { 24. color: black; 25. font-size: 16pt; 26. font-weight: bold; 27. background: #ccc; 28. padding: 0.5em; 29. } 30. #content { 31. height: 50%; 32. background: white; 33. padding: 1em; 34. } 35. #content h1 { 36. font-size: 18pt; 37. } 38. table { 39. text-align: left; 40. }

EVALUATION COPY

Page 40: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-9

Registering Users Navigating to http://localhost:300/admin/register should now present the following view.

• Examination of the HTML source for the above view, as seen by the browser, shows the following form tag.

<form accept-charset="UTF-8" action="/admin/register" method="post">

This requires that an additional route be added to the routes.rb file as shown in bold below.

routes.rb

1. Sessions::Application.routes.draw do 2. get "admin/index" 3. get "admin/login" 4. get "admin/logout" 5. get "admin/register" 6. post "admin/register" 7. ... 8. end

EVALUATION COPY

Page 41: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-10

The Register Action

• With the form in place to collect the data, we can now concentrate on what to do with the data once the form data is submitted.

This, of course, bring us to the register method of the Admin controller.

The code shown in bold below needs to be added to the register method.

admin_controller.rb

1. class AdminController < ApplicationController 2. def index 3. end 4. 5. def login 6. end 7. 8. def logout 9. end 10. 11. def register 12. @title = "Register" 13. if request.post? 14. @user = User.new(params[:user]) 15. if ( @user.save ) 16. session[:user_id] = @user.id 17. flash[:notice] = "Added #{@user.loginname}" 18. redirect_to :action => "index" 19. end 20. end 21. end 22. end

@title = "Register"

• This line makes the string of "Register" available to the views as an instance variable @title.

EVALUATION COPY

Page 42: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-11

The Register Action if request.post? … end

• We saw earlier that when the form was submitted, it relied on an HTTP Post, whereas when the following URL was typed into a browser, it resulted in an HTTP GET. http://localhost:300/admin/register

The request.post? evaluates to true if the form was submitted or false if the action was triggered by a GET request.

• Therefore, the code inside handles the case where the form button was clicked and the data from the form sent.

• Otherwise, the default behavior would be to present the register.html.erb form again.

@user = User.new(params[:user])

• The above code from the method creates a User object out of the fields from the form using the params method.

• The User object is then stored in an instance variable named @user.

The body of the if ( @user.save ) … end statement consists of the following three statements.

session[:user_id][email protected]

• places the id of the user into the session under a key of :user_id

flash[:notice]="Added #{@user.loginname}"

• places a message into a special hash named flash.

redirect_to :action => "index"

• redirects the action to the index action.

EVALUATION COPY

Page 43: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-12

The flash Hash

• The flash is a special part of the session that is cleared with each request.

This means that values stored there will only be available in the next request, which is useful for messages, etc.

It is accessed in much the same way as the session, like a hash.

• Two common keys that are used to store messages in the flash are :notice and :alert.

:notice is often used for simple messages.

:alert is often used for a message of a more serious nature.

• To see the results of messages placed in the flash, we will modify the application.html.erb layout file that acts as the master layout for all of the views of the application.

In addition to providing an overall look and feel for the application by adding links to all of the actions within the application, it will also include the following embedded Ruby tags.

<% if flash[:notice] %> <div id="flash"> <%= flash[:notice] %> </div> <% end %>

• The above code determines if there are any messages in the

flash, and if so, they are displayed.

EVALUATION COPY

Page 44: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-13

The flash Hash application.html.erb

1. <!DOCTYPE html> 2. <html> 3. <head> 4. <title><%= @title %></title> 5. <%= stylesheet_link_tag "application", 6. :media => "all" %> 7. <%= javascript_include_tag "application" %> 8. <%= csrf_meta_tags %> 9. </head> 10. <body> 11. <div id="wholepage"> 12. <div id="header">SESSIONS</div> 13. <div id="links"> 14. <%= link_to "Index", :action => "index" %> | 15. <%= link_to "Logout", :action => "logout" %> | 16. <%= link_to "Login", :action => "login" %> | 17. <%= link_to "Register",:action => "register" %> 18. </div> 19. <% if flash[:notice] %> 20. <div id="flash"> 21. <%= flash[:notice] %> 22. </div> 23. <% end %> 24. <div id="content"><%= yield %></div> 25. </div> 26. </body> 27. </html>

The important changes above will apply to all views within the application.

• The flash has been incorporated. • Many of the HTML tags have an id attribute, which is

utilized within the style sheet for the controller. • Links have been provided to the index, logout, login,

and register actions. The file shown above can be found in the startercode directory for this chapter.

EVALUATION COPY

Page 45: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-14

The flash Hash

• The following pieces are now in place.

Starting with navigating to the index

Followed by clicking the Register link above

EVALUATION COPY

Page 46: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-15

The flash Hash

Followed by clicking the button in the form, not the link

• You should notice the result of the flash in the above view. Notice that if the above page is refreshed, the flash disappears, as shown below.

EVALUATION COPY

Page 47: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-16

Validating the Registration

• We will modify the model to include the following validation code, shown in bold.

user.rb

1. class User < ActiveRecord::Base 2. attr_accessible :email, :loginname, :password 3. 4. NAME_MIN_LENGTH = 4 5. . 6. . 7. . 8. EMAIL_SIZE = 30 9. 10. validates :loginname, :email, :password, 11. :presence => true 12. validates :loginname, :uniqueness => true 13. end

Notice the validation error below if a user tries to re-register.

EVALUATION COPY

Page 48: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-17

Logging in

• Now that we have registered users, we need to provide a way for them to login to the system.

The goal is that you cannot login until you are registered.

• To accomplish this, we first need to create a login view. • It will look very similar to the registration view.

login.html.erb

1. <h2>Log In</h2> 2. <%= form_for :user do |f| %> 3. <%= f.error_messages %> 4. <fieldset><legend>Enter Your Details</legend> 5. <table border="1"> 6. <tr class="form_row"> 7. <td><%= f.label :loginname, "Screen Name" %></td> 8. <td><%= f.text_field :loginname, 9. :size => User::NAME_SIZE, 10. :maxlength => User::NAME_MAX_LENGTH %></td> 11. </tr> 12. <tr class="form_row"> 13. <td><%= f.label :password %></td> 14. <td><%= f.password_field :password, 15. :size => User::PWD_SIZE, 16. :maxlength=>User::PWD_MAX_LENGTH %></td> 17. </tr> 18. <tr class="form_row"> 19. <td colspan="2" align="center"> 20. <%= f.submit "Login!" %></td> 21. </tr> 22. </table> 23. </fieldset> 24. <% end %> 25. <h3>Not a Member? 26. <%= link_to "Register Now", :action => "register" %> 27. </h3>

The file above can be found in the startercode directory for this chapter and should overwrite the existing file located in the app/views/admin directory.

EVALUATION COPY

Page 49: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-18

Logging In

• With the login.html.erb form in place, we now concentrate on the login action of the Admin controller.

Much like the register action, the login action will begin by determining if the incoming request is a POST from the form or a GET from a link.

admin_controller.rb

1. class AdminController < ApplicationController 2. def login 3. @title = "Login Page" 4. if request.post? and params[:user] 5. @user = User.new(params[:user]) 6. user = User.find_by_loginname_and_password \ 7. @user.loginname, @user.password 8. if user 9. session[:user_id] = user.id 10. flash[:notice] = 11. "#{user.loginname} logged in." 12. redirect_to :action => "index" 13. else 14. @user.password = nil 15. @user.loginname = nil 16. flash[:notice] = 17. "screen name/password: no match" 18. end 19. end 20. end 21. 22. def index 23. end 24. 25. def logout 26. end 27. 28. def register 29. ... 30. end 31. end

EVALUATION COPY

Page 50: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-19

Logging In

• The code on the previous page determines if the request is a POST request and whether the params[:user] exists.

• If the above requirement is not met, the form is redisplayed. If it is met, the following happens.

A User object is created and stored in the @user instance variable.

@user = User.new(params[:user])

The following method is then built by Rails using reflection.

user = User.find_by_loginname_and_password \ (@user.loginname, @user.password)

It scans the users table in the database to see if the loginname and password in the database match those values from the form.

• If there is a match, the user is logged in (saved in the session hash), a flash notice is given, and the index template is displayed. session[:user_id] = user.id flash[:notice] = "#{user.loginname} logged in." redirect_to :action => "index"

• Otherwise, the fields in the form are set to nil and the form is

reproduced. @user.password = nil @user.loginname = nil flash[:notice] = "screen name/password: no match"

EVALUATION COPY

Page 51: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-20

Logging in

• Once again, there is a form tag in the login view that relies on an HTTP POST in the view on the previous page.

As such, yet another route will have to be added to the routes.rb file.

routes.rb

1. Sessions::Application.routes.draw do 2. get "admin/index" 3. get "admin/login" 4. get "admin/logout" 5. get "admin/register" 6. post "admin/register" 7. post "admin/login" 8. ... 9. end

EVALUATION COPY

Page 52: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-21

Logging Out

• Eventually, a user will want to logout.

The logout action within the controller is fairly straightforward and is shown in bold below.

def logout session[:user_id] = nil flash[:notice] = "Logged out" redirect_to :action => "index" end • The above code should be added to the

admin_controller.rb file.

• However, there are certain logical considerations to take into account.

A logged in user should not be presented with a login link.

A user who is not logged in should not be given a logout link.

• Since it is the layout file application.html.erb currently providing the links, it is here that the logic should account for the above scenarios.

• The four links in that file should be modified as follows. <div id="links"> <% if session[:user_id] %> <%= link_to "Index", :action => "index" %> | <%= link_to "Logout", :action => "logout" %> <% else %> <%= link_to "Login", :action => "login" %> | <%= link_to "Register",:action => "register" %> <% end %> </div>

• A logged in user should now see only the Index and Logout links.

• When not logged in, they should see the Login and Register links.

EVALUATION COPY

Page 53: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-22

Protected Pages

• Many web sites require a registration and a login capability.

Access to the resources on these sites is restricted to registered users who have logged in.

• These type of resources would be considered protected resources.

• In a Rails application, this means that any request to a protected page should involve the checking of the session hash first.

The code that offers the protection should be made private within the appropriate controller.

private def protect unless session[:user_id] flash[:notice] = "Please log in first" redirect_to :action => "login" return false end end

• When an attempt is made to visit a protected page, the protect method is executed and determines the view presented to the user.

EVALUATION COPY

Page 54: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-23

Filters

• In order to assure that the protect method defined within the controller code is executed, Rails relies on a before_filter.

• The before_filter would be coded as follows inside of a controller.

The examples that follow assume there may be a controller named SomeController.

• This controller does not actually exist but is used only to demonstrate the following. class SomeController < ApplicationController before_filter :protect ... end

• The above example will result in the protect method being called before every action in the controller.

The following code demonstrates how to apply the before filter to only certain actions.

class SomeController < ApplicationController before_filter :protect, :only => "index" ... end

• The above example would filter only calls to the index action in the controller.

You can allow the before_filter to exclude certain action.

class SomeController < ApplicationController before_filter :protect, :except => [:action01, :action02] ... end

• Rails also provides an after_filter, similar in design to the before_filter described above.

EVALUATION COPY

Page 55: Table of Contents€¦ · RUBY ON RAILS 3 ©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: AN OVERVIEW OF RUBY ON RAILS What

RUBY ON RAILS 3 CHAPTER 6: USERS

©2013 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. 6-24

Exercises 1. You will work on a copy of the Sessions application from

this chapter.

A copy of it is available as a new application named MoreSessions within the startercode directory for this chapter.

• The directory itself should be copied to the railsapps directory.

2. Once the application is copied over, create a second controller named "Purchases" that has the following actions.

buy, sell, and list

3. Modify the index.html.erb of the admin views to have links to the above three actions.

Hint: the link_to method allows the controller to be specified, as shown below.

<%= link_to 'Buy', :action => "buy", :controller => "purchases" %>

4. The above three links should be considered protected resources.

Make sure the user is logged in before they have access to them.

If they are not logged in, they should be redirected to the index page of the admin controller.

EVALUATION COPY