Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | A Database-Driven Web Application - 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

A Database-Driven Web Application - Ruby on Rails

The third tier of a typical Rails application—the model—manages the data used in the application.

A Database-Driven Web Application


The third tier of a typical Rails application—the model—manages the data used in the application. In this section, we set up a database and build a fully functional web application using the ActionView and ActionController classes that we introduced in Section 24.4. We create an application that allows the user to browse and edit an employee list. To create this application’s structure, type rails Employees in the Ruby Console window.


Object Relational Mapping


Rails makes extensive use of Object-Relational Mapping (ORM) in its web framework. ORM maps a table to application objects. The objects that Rails uses to encapsulate a da tabase inherit from ActiveRecord. By using ActiveRecord and Rails conventions, you can avoid a lot of explicit configuration.


One ActiveRecord convention is that every model that extends ActiveRecord::Base


in an application represents a table in a database. The table that the model represents is, by convention, the lowercase, pluralized form of the model. For example, if there were a messages table in your database, Message would be the name of the model representing it. ActiveRecord follows many standard English pluralization rules as well, which means that a Person model would automatically correspond to a people table. Furthermore, if a people table has a first_name column, the Person model would have a method named first_name that returns the value in that column. ActiveRecord does this for you with no additional configuration.


Creating the Database


Before creating a model using ActiveRecord, we need to create the database it will use. You can do that using MySQL’s mysqladmin command. Rails will automatically look for a da-tabase with the name applicationName_development to use as the development database. To create a database for the Employees application, launch the Ruby Console and type in mysqladmin -u root create employees_development. If no error is returned, the database was created successfully in the mysql/data directory of your InstantRails installation.


By default MySQL has the user name root and no password. If your settings are dif-ferent you can modify the appropriate fields database.yml, located in the config folder in your application directory.


Creating the Employee Model

Since Rails separates the model from the rest of the application, we simply need to put the Employee class definition in the models directory. Rails uses a generator to create the mod-el for the employees table, which you use by navigating to your application directory then typing ruby script/generate model employee in the Ruby Console. The result is shown in Fig. 24.17.


The last line the console returns is create db/migrate/001_create_employees.rb.

We have not yet created a table employees, so Ruby automatically generates a script that will create this table when the application launches. We can modify this script to perform additional initial changes to the employees table. Figure 24.19 shows a modification of 001_create_employees.rb (located in your application’s db/migrate directory) that creates the table and adds three records to it.


ActiveRecord has a special feature called Migration, which allows you to preform database operations within Rails. Each object that inherits from ActiveRecord::Migra-

Running Ruby on Rails


A Ruby on Rails application must be run from a web server. In addition to Apache, Instant Rails comes with a built-in web server named Mongrel, which is easy to use to test Rails applications on the local machine. You can start the Mongrel server through Instant Rails by going to the Rails Application window, selecting the Welcome application from the list and clicking the Start with Mongrel button (Fig. 24.13).


One important feature of Rails is its URL mapping ability. Rails automatically sets up your web application in a tree structure, where the controller’s name in lowercase is the directory, and the method name is the subdirectory. Since the controller name is Welcome and the method name is index, the URL to display the text in Figure 24.12 is  http:// localhost:3000/welcome/index. Notice in the screen capture of Figure 24.12 that the URL is simply  http://localhost:3000/welcome. The default action called on any controller is the one specified by the method index. So, you do not need to explicitly invoke the index in the URL to render the text in line 6.

1    # Fig. 24.18: db/migrate/001_create_employees.rb


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


3    class CreateEmployees < ActiveRecord::Migration


4          # create the table with three columns and insert some rows.


5          def self.up

6       create_table  :employees do |t|


7                       t.column :first_name, :string


8                       t.column :last_name, :string


9                       t.column :job_title, :string


10                end # do block


12                Employee.create :first_name => "Sue", :last_name => "Green",


13                      :job_title => "Programmer"


14                Employee.create :first_name => "Meg", :last_name => "Gold",


15                      :job_title => "Programmer"


16                Employee.create :first_name => "John", :last_name => "Gray",


17                      :job_title => "Programmer"


18         end # method self.up


20         # reverse the migration, delete the table that was created


21         def self.down


22                drop_table :employees


23         end # method self.down


24   end # class CreateEmployees


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


tion must implement two methods—self.up (lines 5–18), which preforms a set of data-base operations, and self.down (lines 21–23), which reverses the database operations performed in self.up. In this case self.up creates the table with three columns and adds data to it, and self.down deletes the table. Line 6 calls the create_table function passing as a parameter a code block, inside the do, containing the table’s column names and types.


Lines 12–17 use ActiveRecord’s built in create method to add data to the Employees table. ActiveRecord has built-in functionality for many create, retrieve, update, and destroy methods—known in Rails as CRUD. These methods represent the trivial opera-tions that you would want to do with a database.


We can execute the migration using Ruby’s rake command. To do so open up the Ruby Console, navigate to your application’s directory and type rake db:migrate. This command will call the self.up method of all the migrations located in your db/migrate directory. If you ever want to roll back the migrations you can type in rake db:migrate VERSION=0, which calls each migration’s self.down method. Specifying a version number other than 0 will call the self.down method of all the migrations whose number is greater then the version number.

Because our model will never be modified by the application, we do not need to add any functionality to it. Figure 24.19, which represents the employee.rb file located in the app/Models directory, contains all the code that is needed to integrate the employees data-base table into the application.



1    # Fig. 24.19: employee.rb


2    # Generated code for an Employee Model.


3    class Employee < ActiveRecord::Base


4    end # class Employee


Fig. 24.19 | Generated code for an Employee model.


Employee Controller


Next, create the controller with the ruby script/generate controller employees command as shown in Section 24.4. Figure 24.20 shows the example controller for the Em-ployee application. Line 4 calls the scaffold method. This is a powerful tool that automatically creates CRUD functionality. It creates methods such as new, edit and list so you don’t have to create them yourself. It also defines default views for these methods that are rendered when each method is called. You can override the default functionality by defining your own methods. If you override all the CRUD methods you can delete the scaffold method. When you override a method, you must also create the corresponding view. Since we will not modify the new method created by the scaffold you can see the new method’s view with the URL  http://localhost:3000/employee/new (Figure 24.21).


Line 7–9 override the list method. Line 8 queries the database and returns a list of all of the Employee objects, which gets stored in an @employees instance array. This data will be passed to the view.


The list View

The list template is rendered by the list method from the EmployeeController. Code for the list template is shown in Fig. 24.22. This file should be placed in your applica-tion’s app/views/employee directory. While most of it is just standard XHTML, lines 14– 17 contain Ruby code that iterates through all the employees in the @employees array in-stance variable, and outputs each employee’s first and last name (line 16). A for statement like this in a list view is common in database-driven web applications.



1     # Fig. 24.20: app/controllers/employees_controller.rb


2     # Provides all of the functionality for the application.


class EmployeesController < ApplicationController

4          scaffold :employee                

5          # create scaffold code for controller           

6           # override scaffold list method


7           def list


8                  @employees = Employee.find( :all ) # return an array of Employees


9           end # method list


end # class EmployeeController

Fig. 24.20 | Employee controller provides all of the functionality for the application.


Fig. 24.21 | View of the new action when generated by the scaffold.


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">


5    <!-- Fig. 24.22 app/views/employees/list.rhtml -->


6    <!-- A view that displays a list of Employees. -->


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


8    <head>


9          <title>List of Employees</title>


10   </head>


11   <body style="background-color: lightyellow">


12         <h1>List of Employees</h1>

13         <ol>


14         <% for employee in @employees %>


15         <!-- create a list item for every employee with his full name -->


16               <li><%= employee.first_name %> <%= employee.last_name %></li>


17         <% end %>


18         </ol>


19   </body>





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

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