Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Message Forum: Logging In and Logging Out - Ruby on Rails

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Ruby on Rails

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

Message Forum: Logging In and Logging Out - Ruby on Rails

Use the model generator to generate the User model by typing ruby script/generate model User into the Ruby Console (from the Messageboard directory).

Logging In and Logging Out

 

Use the model generator to generate the User model by typing ruby script/generate model User into the Ruby Console (from the Messageboard directory). Next, create the ta-ble that will be associated with the model. To do that, modify the migration created by the model generator to set up the users table and add some data to it. Figure 24.23 is the 001_create_users.rb migration (from the db/migrate directory) which sets up the user table.

 

The create_table function call (lines 6–9) specifies the table’s columns. By default a primary key id column is created, so it is not included here. Lines 7–8 create the name and password columns with appropriate types. Note that the name has a limit of 11 char-acters. Line 11 adds data to the table. To execute this migration type rake db:migrate in the Ruby Console.

 

1    # Fig. 24.23: db/migrate/001_create_users.rb

 

2    # Database migration script modified to add data to the table.

 

3    class CreateUsers < ActiveRecord::Migration

 

4          # create and configure users table

 

5          def self.up

 

6                 create_table :users do |t|

 

7                       t.column :name, :string, :limit => 11

 

8                       t.column :password, :string

 

end # do block

10

11                User.create :name => "user1", :password => "54321"

 

12         end # method self.up

13

14         # remove users table

 

15         def self.down

 

16                drop_table :users

 

17         end # method self.down

 

18   end # class CreateUsers

 

Fig. 24.23 | Database migration script modified to add data to the table.

Since the users table never changes, nothing needs to be specified in the User model, but one still needs to exist. This will allow the controller to access a User as an ActiveRecord. Figure 24.24 shows the empty model for the users table.

 

Next, we need to provide user creation, field validation and user logout functionality through the use of a controller (Fig. 24.25). Create this controller by typing ruby script/ generate controller user. When a user logs in, we will keep track of that User object in a session variable—a variable that maintains information across multiple pages of a web application. The purpose of the admin method (lines 5–7) is to pass a blank user object into the admin page, which will get filled with information, then render the admin.rhtml template. The validate method (lines 10–21) checks the user model to determine

 

# Fig. 24.24: app/models/user.rb

 

# Generated code for the User model.

 

class User < ActiveRecord::Base

 

end # method User

 

Fig. 24.24 | Generated code for the User model.

 

1     # Fig. 24.25: app/controllers/users_controller.rb

 

2     # UsersController provides validation functionality for the table.

 

3     class UsersController < ApplicationController

 

4           # create a new User object

 

5           def admin

 

6                  @user = User.new # create a new User object

 

7           end # method admin

8

9           # validate that user exists

 

10          def validate

 

11                 # find a user with the correct name and password

 

12                 @user = User.find_by_name_and_password(  params[ :user ][ :name ],

 

params[ :user ][ :password ] )

15                 if ( @user == nil )  # if the user dosn’t exist

 

16                       redirect_to :action => "admin" # redirect to admin action

 

17                 else # user does exist

 

18                       session[ :user ] = @user # store the user in a session variable

 

19                       redirect_to :controller => "forums", :action => "index"

 

20                 end # if

 

21          end # method validate

22

23          # log user out

 

24          def logout

 

25                 reset_session # delete all session variables

 

26                 redirect_to :controller => "forums", :action => "index" # redirect

 

27          end # method logout

 

28    end # class UserController

 

Fig. 24.25 | UsersController provides validation functionality for the table.

whether the username exists, then redirects the application to the next action based on the result of that check.

 

Rails allows us to generate methods dynamically to serve a specific purpose. Lines 12–13 call the find_by_name_and_password method, which searches the model with the name and password, passed as a parameter.

 

The validate method assigns to an instance variable named @user (line 12) the value of the User that was returned by the find_by_name_and_password method. If no such User exists, the client is redirected to the admin page and asked to log in again (line 16). If the User does exist, a session variable is created (line 18), and line 19 redirects the client to the index of the forums controller, which we create in Section 24.6.4. The logout method (lines 24–27) uses the reset_session method to delete all the user’s session vari-ables, forcing the user to sign in again to use administrative options.

Method admin’s view is a simple login form. The template is shown in Fig. 24.26. It asks the user for a name and password using the text_field (line 6) and password_field (line 9) helpers, then sends the information to the validate method when the user clicks Sign In.

1    <!-- Fig. 24.26: app/views/users/admin.rhtml -->

 

2    <!-- Login form used to send data to the user controller. -->

 

3    <h1>Please Log In</h1>

 

4    <% form_tag :action => 'validate' do %> <!-- create form tag -->

 

<p><label for="user_name">Name</label><br/>

<%= text_field 'user', 'name'  %>    

</p> <!-- create input tag --> 

8          <p><label for="user_password">Password</label><br/>

 

9          <%= password_field 'user', 'password'  %></p> <!-- create input tag -->

 

10         <%= submit_tag "Sign In" %> <!-- create submit tag -->

 

<% end %> <!-- create an end form tag -->


Fig. 24.26 | Login form used to send data to the user controller.

Rails helpers are methods that generate XHTML content for the view. The password_field helper method generates a text field that masks the text inside it. Both text_field and password_field specify a model and the column. This information is used to determine the validation properties for each column when validating the text typed into these fields. When the user clicks the submit button defined in line 10, the form_tag method (line 4) automatically generates a Hash, where the keys are the names of the input fields and the values are what the user entered, and sends it to the validate action. The link to the validate action is specified by the action option. To display this action, run the Mongrel server and navigate your browser to  http://localhost:3000/user/admin.

 

We define the user controller’s template in Fig. 24.27. Because the user controller has only a single view to render, we could have simply include this XHTML in the view. The benefit of a template is that it allows us to easily add more views in the future that are all based on the same template and adhere to Ruby on Rails’ DRY (Don’t Repeat Yourself) philosophy. Line 9 displays the current action in the title bar. Line 12 is the placeholder for the content of the action’s view.

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 24.27: app/views/layouts/users.rhtml-->

 

6    <!-- Display the name of the current action in the title bar -->

 

7     <html xmlns = "http://www.w3.org/1999/xhtml">

8     <head>

 

9     <title>Users: <%= controller.action_name %></title>

 

10 </head>

 

11 <body>

 

12 <%= yield %>

 

13 </body>

 

14 </html>

 

Fig. 24.27 | Display the name of the current action in the title bar


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.