Rails

43
To develop a web application using Ruby on Rails Framework, install the following software: * Ruby * The Rails framework * A Web Server * A Database System We assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production. Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database. Ruby on Rails Installation

Transcript of Rails

Page 1: Rails

To develop a web application using Ruby on Rails Framework, install the following software:

* Ruby * The Rails framework * A Web Server * A Database System

We assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production.

Rails works with many database systems, including MySQL,PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database.

Ruby on Rails Installation

Page 2: Rails

1. First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2 then type gem --version. If you don't get an error, skip to step 3. Otherwise, we'll install a fresh Ruby.

2. If Ruby is not installed, then download an installation package from rubyinstaller.rubyforge.org. Follow the download link, and run the resulting installer. This is an exe like ruby186-25.exe and will be installed in a single click. You may as well install everything . It's a very small package, and you'll get RubyGems as well alongwith this package. Please check Release Notes for more detail.

3. With RubyGems loaded, you can install all of Rails and its dependencies through the command line:

C:\> gem install rails --include-dependencies

Page 3: Rails

Architecture of Rails Applications

Page 4: Rails

Ruby on Rails MVC framework:

The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems.

Model

Maintains the relationship between Object and Database and handles validation, association, transactions, and more.

View

This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

Controller

The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand organizing that data (searching, sorting, massaging it) into a form that fits the needs of a given view.

Page 5: Rails

Building an Application

Creating an Empty Rails Web Application:

Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application.

1. Go into ruby installation directory to create your application. 2. Run the following command to create a skeleton for library application.

C:\ruby> rails hello

This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application

Page 6: Rails

Ruby on Rails Directory Structure

When you use the rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to tell it.

Here is a top level view of directory tree created by helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization.

To understand this directory structure let's use demo application created in installation chapter. This can be created using a simple helper command C:\ruby\> rails helloNow go into demo application root directory as follows:

C:\ruby\> cd helloC:\ruby\hello> dir

Page 7: Rails

You will find a directory structure as follows:

demo/..../app......../controller......../helpers......../models......../views............../layouts..../components..../config..../db..../doc..../lib..../log..../public..../script..../test..../tmp..../vendorREADMERakefile

Page 8: Rails

app : This organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).

app/controllers: The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

app/helpers: The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

app/models: The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!

app/view: The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

Page 9: Rails

config: This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.

db: Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.

Page 10: Rails

Starting up the Web Server

You actually have a functional Rails application already – after running only two commands! To see it, you need to start a web server on your development machine. You can do this by running another command:

script/server

This will fire up an instance of the Mongrel web server by default (Rails can also use several other web servers). To see your application in action, open a browser window and navigate to http://localhost:3000. You should see Rails’ default information page:

Page 11: Rails

Rails Database Setup

Configuring database.yml:

At this point, you need to let Rails know about the user name and password for the databases. You do this in the file database.yml, available in the C:\ruby\library\config subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the username and password lines to reflect the permissions on the databases you've created.

Page 12: Rails

When you finish, it should look something like:

development: adapter: mysql database: library_development username: root password: [password] host: localhost

Page 13: Rails

Translating a domain model into SQL:

Translating a domain model into SQL is generally straightforward, as long as you remember that you have to write Rails-friendly SQL. In practical terms you have to follow certain rules:

* Each entity (such as book) gets a table in the database named after it, but in the plural (books).

* Each such entity-matching table has a field called id, which contains a unique integer for each record inserted into the table.

Page 14: Rails

Creating Active Record files:

To create the Active Record files for our entities for library application, introduced in the previous chapter, issue the following command from the top level of the application directory.

C:\ruby\library\> ruby script/generate model BookC:\ruby\library\> ruby script/generate model Subject

You're telling the generator to create models called Book, and Subject to store instances of books and subjects. Notice that you are capitalizing Book and Subject and using the singular form. This is a Rails paradigm that you should follow each time you create a model.

When you use the generate tool, Rails creates the actual model file that holds all the methods unique to the model and the business rules you define, a unit test file for performing test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration that makes creating database tables and columns easy.

Apart from creating many other files and directories, this will create files named book.rb and subject.rb containing a skeleton definition in app/models directory.

Page 15: Rails

Content available in book.rb

class Book < ActiveRecord::Baseend

Content available in subject.rb

class Subject < ActiveRecord::Baseend

Page 16: Rails

Module

ActionView::Helpers::FormTagHelper

* check_box_tag * file_field_tag * form_tag * hidden_field_tag * image_submit_tag * label_tag * password_field_tag * radio_button_tag * select_tag * submit_tag * text_area_tag * text_field_tag

Page 17: Rails

check_box_tag(name, value = "1", checked = false, options = {})

Options

* :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML options for the tag.

Creates a check box form input tag.

check_box_tag

check_box_tag 'accept' # => <input id="accept" name="accept" type="checkbox" value="1" />

check_box_tag 'rock', 'rock music' # => <input id="rock" name="rock" type="checkbox" value="rock music" />

Examples

Page 18: Rails

Examples

file_field_tag(name, options = {})

Creates a file upload field. If you are using file uploads then you will also need to set the multipart option for the form tag:

<% form_tag '/upload', :multipart => true do %> <label for="file">File to Upload</label> <%= file_field_tag "file" %> <%= submit_tag %> <% end %>

file_field_tag 'attachment' # => <input id="attachment" name="attachment" type="file" />

Page 19: Rails

form_tag(url_for_options = {}, options = {})

Starts a form tag that points the action to an url configured with url_for_options just like ActionController::Base#url_for. The method for the form defaults to POST.

Options

* :multipart - If set to true, the enctype is set to "multipart/form-data". * :method - The method to use when submitting the form, usually either "get" or "post". If "put", "delete", or another verb is used, a hidden input with name _method is added to simulate the verb over post. * A list of parameters to feed to the URL the form will be posted to. form_tag('/posts')

# => <form action="/posts" method="post">

form_tag('/posts/1', :method => :put) # => <form action="/posts/1" method="put">

Examples

Page 20: Rails

password_field_tag(name = "password", value = nil, options = {})

Creates a password field, a masked text field that will hide the users input behind a mask character.

Options

* :disabled - If set to true, the user will not be able to use this input. * :size - The number of visible characters that will fit in the input. * :maxlength - The maximum number of characters that the browser will allow the user to enter. * Any other key creates standard HTML attributes for the tag.

password_field_tag 'pass' # => <input id="pass" name="pass" type="password" />

password_field_tag 'secret', 'Your secret here' # => <input id="secret" name="secret" type="password" value="Your secret here" />

Examples

Page 21: Rails

radio_button_tag(name, value, checked = false, options = {})

Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options.

Options

* :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML options for the tag.Examples

radio_button_tag 'gender', 'male' # => <input id="gender_male" name="gender" type="radio" value="male" />

radio_button_tag 'receive_updates', 'no', true # => <input checked="checked" id="receive_updates_no" name="receive_updates" type="radio" value="no" />

Page 22: Rails

select_tag(name, option_tags = nil, options = {})

Creates a dropdown selection box, or if the :multiple option is set to true, a multiple choice selection box.

Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or associated records. option_tags is a string containing the option tags for the select box.

Options

* :multiple - If set to true the selection will allow multiple choices. * :disabled - If set to true, the user will not be able to use this input. * Any other key creates standard HTML attributes for the tag.

Page 23: Rails

Examples

select_tag "people", "<option>David</option>" # => <select id="people" name="people"><option>David</option></select>

select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>" # => <select id="count" name="count"><option>1</option><option>2</option> # <option>3</option><option>4</option></select>

Page 24: Rails

submit_tag(value = "Save changes", options = {})

Creates a submit button with the text value as the caption.

Options

* :confirm => ‘question?‘ - This will add a JavaScript confirm prompt with the question specified. If the user accepts, the form is processed normally, otherwise no action is taken. * :disabled - If true, the user will not be able to use this input. * :disable_with - Value of this parameter will be used as the value for a disabled version of the submit button when the form is submitted. * Any other key creates standard HTML options for the tag.Examples submit_tag # => <input name="commit" type="submit" value="Save changes" />

submit_tag "Edit this article" # => <input name="commit" type="submit" value="Edit this article" />

Page 25: Rails

text_area_tag(name, content = nil, options = {})

Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.

Options

* :size - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10"). * :rows - Specify the number of rows in the textarea * :cols - Specify the number of columns in the textarea * :disabled - If set to true, the user will not be able to use this input. * :escape - By default, the contents of the text input are HTML escaped. If you need unescaped contents, set this to false. * Any other key creates standard HTML attributes for the tag.

Page 26: Rails

Examples

text_area_tag 'post' # => <textarea id="post" name="post"></textarea>

text_area_tag 'bio', @user.bio # => <textarea id="bio" name="bio">This is my biography.</textarea>

text_area_tag 'body', nil, :rows => 10, :cols => 25 # => <textarea cols="25" id="body" name="body" rows="10"></textarea>

Page 27: Rails

text_field_tag(name, value = nil, options = {})

Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.

Options

* :disabled - If set to true, the user will not be able to use this input. * :size - The number of visible characters that will fit in the input. * :maxlength - The maximum number of characters that the browser will allow the user to enter. * Any other key creates standard HTML attributes for the tag.Examples

text_field_tag 'name' # => <input id="name" name="name" type="text" />

text_field_tag 'query', 'Enter your search query here' # => <input id="query" name="query" type="text" value="Enter your search query here" />

Page 28: Rails

The Basics, Relationships between Tables

Tables and Classes

Page 29: Rails

When we create a subclass of ActiveRecord::Base, we’re creating something that wraps a database table. By default, Active Record assumes that the name of the table is the plural form of the name of the class. If the class name contains multiple capitalized words, the table name is assumed to have underscores between these words. Some irregular plurals are handled.

class Sheep < ActiveRecord::Baseset_table_name "sheep" # Not "sheeps"End

class Order < ActiveRecord::Baseset_table_name "ord_rev99_x" # Wrap a legacy table...End

If you don’t like methods called set_xxx, there’s also a more direct form:

class Sheep < ActiveRecord::Baseself.table_name = "sheep"end

Page 30: Rails

Columns and Attributes

Active Record objects correspond to rows in a database table. The objects have attributes corresponding to the columns in the table. You probably noticed that our definition of class Order didn’t mention any of the columns in the orders table. That’s because Active Record determines them dynamically at runtime. Active Record reflects on the schema inside the database to configure the classes that wrap tables.

def self.upcreate_table :orders do |t|t.string :namet.text :addresst.string :emailt.string :pay_type, :limit => 10t.timestampsendend

Page 31: Rails

So, all we have to do is run the migration:

demo> rake db:migrate

Page 32: Rails

Relationships between Tables

One-to-One Relationships

Page 33: Rails

One-to-One Relationships

A one-to-one association (or, more accurately, a one-to-zero-or-one relationship) is implemented using a foreign key in one row in one table to reference at most a single row in another table. A one-to-one relationship might exist between orders and invoices: for each order there’s at most one invoice.

As the example shows, we declare this in Rails by adding a has_one declaration to the Order model and by adding a belongs_to declaration to the Invoice model. There’s an important rule illustrated here: the model for the table that contains the foreign key always has the belongs to declaration.

Page 34: Rails

One-to-Many Relationships

Page 35: Rails

One-to-Many Relationships

A one-to-many association allows you to represent a collection of objects. For example, an order might have any number of associated line items. In the database, all the line item rows for a particular order contain a foreign key column referring to that order.

In Active Record, the parent object (the one that logically contains a collection of child objects) uses has_many to declare its relationship to the child table, and the child table uses belongs_to to indicate its parent. In our example, class LineItem belongs_to :order, and the orders table has_many :line_items.

Note that again, because the line item contains the foreign key, it has the belongs_to declaration.

Page 36: Rails

Many-to-Many Relationships

Page 37: Rails

Many-to-Many Relationships

Finally, we might categorize our products. A product can belong to many categories, and each category may contain multiple products. This is an example of a many-to-many relationship. It’s as if each side of the relationship contains a collection of items on the other side.

Create, Read, Update, Delete (CRUD)

Active Record makes it easy to implement the four basic database operations: create, read, update, and delete.In this section we’ll be working with our orders table in a MySQL database. The following examples assume we have a basic Active Record model for this table:

class Order < ActiveRecord::Baseend

Page 38: Rails

Creating New Rows

In the object-relational paradigm, tables are represented as classes, and rows in the table correspond to objects of that class. It seems reasonable that we create rows in a table by creating new objects of the appropriate class. We can create new objects representing rows in our orders table by calling Order.new. We can then fill in the values of the attributes (corresponding to columns in the database). Finally, we call the object’s save method to store the order back into the database. Without this call, the order would exist only in our localmemory.

Page 39: Rails

an_order = Order.newan_order.name = "Dave Thomas"an_order.email = "[email protected]"an_order.address = "123 Main St"an_order.pay_type = "check"an_order.save

Active Record constructors take an optional block. If present, the block is invoked with the newly created order as a parameter. This might be useful if you wanted to create and save away an order without creating a new localvariable.

Page 40: Rails

Reading Existing Rows

Reading from a database involves first specifying which particular rows of data you are interested in—you’ll give Active Record some kind of criteria, and it will return objects containing data from the row(s) matching the criteria. The simplest way of finding a row in a table is by specifying its primary key. Every model class supports the find method, which takes one or more primary key values. If given just one primary key, it returns an object containing data for the corresponding row (or throws a RecordNotFound exception). If given multiple primary key values, find returns an array of the corresponding objects.

Note that in this case a RecordNotFound exception is raised if any of the idscannot be found (so if the method returns without raising an error, the lengthof the resulting array will be equal to the number of ids passed as parameters):

an_order = Order.find(27) # find the order with id == 27

Page 41: Rails

pos = Order.find(:all, :conditions => "name = 'Dave' and pay_type = 'po'" )

Using Like Clauses

# get the name from the formname = params[:name]

# DON'T DO THIS!!!

pos = Order.find(:all,:conditions => "name = '#{name}' and pay_type = 'po'" )

User.find(:all, :conditions => ["name like ?" , params[:name]+"%" ])

Page 42: Rails

Writing Our Own SQL

The find method constructs the full SQL query string for us. The method find_by_sql lets our application take full control. It accepts a single parameter containing a SQL select statement (or an array containing SQL and placeholder values, as for find) and returns a (potentially empty) array of model

orders = Order.find_by_sql("select name, pay_type from orders" )

Page 43: Rails

Getting Column Statistics

Rails 1.1 added the ability to perform statistics on the values in a column. For example, given a table of orders, we can calculate the following:

average = Order.average(:amount) # average amount of ordersmax = Order.maximum(:amount)min = Order.minimum(:amount)total = Order.sum(:amount)number = Order.count

These all correspond to aggregate functions in the underlying database, but they work in a database-independent manner. If you want to access databasespecific functions, you can use the more general-purpose calculate method. For example, the MySQL std function returns the population standard deviation ofan expression