Rails 2.1 Database Setup

Ruby on Rails 2.1 – Database Setup ”; Previous Next Before starting with this chapter, make sure your database server is setup and running. Ruby on Rails recommends to create three databases – a database each for development, testing, and production environment. According to convention, their names should be as follows − library_development library_production library_test You should initialize all three of them and create a username and password for them with full read and write privileges. We are using root user ID for our application. In MySQL, a console session looks as follows − mysql> create database library_development; Query OK, 1 row affected (0.01 sec) mysql> use library_development; Database changed mysql> grant all privileges on library_development.* to ”root”@”localhost” identified by ”password”; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) You can do the same thing for the other two databases, library_production and library_test. Configuring database.yml At this point, you need to let Rails know about the username and password for the databases. You do this in the file database.yml, available in the C:rubylibraryconfig 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. When you finish, it should look something like − development: adapter: mysql encoding: utf8 database: library_development username: root password: password host: localhost test: adapter: mysql encoding: utf8 database: library_test username: root password: password host: localhost production: adapter: mysql encoding: utf8 database: library_production username: root password: password host: localhost NOTE − You can use similar setting for other databases if you are using any other database except MySQL. What is Next? The next two chapters explain how to model your database tables and how to manage those using Rails Migrations. Print Page Previous Next Advertisements ”;

Rails 2.1 Basic HTTP Auth

Ruby on Rails 2.1 – HTTP Basic Authentication ”; Previous Next Rails provides various ways of implementing authentication and authorization. But the simplest one is a new module, which has been added in Rails 2.0. This module is a great way to do API authentication over SSL. To use this authentication, you will need to use SSL for traffic transportation. In our tutorial, we are going to test it without an SSL. Let us start with our library example that we have discussed throughout the tutorial. We do not have much to do to implement authentication. We will add a few lines in blue in our ~library/app/controllers/book_controller.rb: Finally, your book_controller.rb file will look as follows − class BookController < ApplicationController USER_ID, PASSWORD = “zara”, “pass123″ # Require authentication only for edit and delete operation before_filter :authenticate, :only => [ :edit, :delete ] def list @books = Book.find(:all) end def show @book = Book.find(params[:id]) end def new @book = Book.new @subjects = Subject.find(:all) end def create @book = Book.new(params[:book]) if @book.save redirect_to :action => ”list” else @subjects = Subject.find(:all) render :action => ”new” end end def edit @book = Book.find(params[:id]) @subjects = Subject.find(:all) end def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to :action => ”show”, :id => @book else @subjects = Subject.find(:all) render :action => ”edit” end end def delete Book.find(params[:id]).destroy redirect_to :action => ”list” end def show_subjects @subject = Subject.find(params[:id]) end private def authenticate authenticate_or_request_with_http_basic do |id, password| id == USER_ID && password == PASSWORD end end end Let us explain these new lines − The first line is just to define the user ID and password to access various pages. In the second line, we have put before_filter, which is used to run the configured method authenticate before any action in the controller. A filter may be limited to specific actions by declaring the actions to include or exclude. Both options accept single actions (:only => :index) or arrays of actions (:except => [:foo, :bar]). So here we have put authentication for edit and delete operations only. Due to the second line, whenever you would try to edit or delete a book record, it will execute private authenticate method. A private authenticate method is calling uthenticate_or_request_with_http_basic method, which comprises of a block and displays a dialogue box to ask for User ID and Password to proceed. If you enter a correct user ID and password then it will proceed, otherwise it would display ‘access denied’. Now, try to edit or delete any available record, to do so you would have to go through the authentication process using the following dialogue box. Print Page Previous Next Advertisements ”;

Rails 2.1 Installation

Ruby on Rails 2.1 – Installation ”; Previous Next To develop a web application using Ruby on Rails Framework, you would need to 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 standard installation of 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. Let”s look at the installation instructions for Rails” Framework on Windows, Mac OS X, and Linux. Rails Installation on Windows First, let”s check to see if you already have Ruby installed. Bring up a command prompt and type C:> ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.6, then type C:> gem –version. If you don”t get an error, skip to step 3. Otherwise, we”ll do a fresh installation for Ruby. 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 along with this package. With RubyGems loaded, you can install all of Rails and its dependencies through the command line − C:> gem install rails –include-dependencies The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Windows. NOTE − In case you face any problem with the above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So just issue the following command and you will have everything updated automatically. C:> gem update Then try above command with updated gems. Rails Installation on Mac OS X 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.6 then skip to step 3. Otherwise, we”ll do a fresh installation for Ruby. To install a fresh copy of Ruby, the Unix instructions that follow should help. Next, you have to install RubyGems. Go to rubygems.rubyforge.org and follow the download link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type the following − tp> tar xzf rubygems-0.8.10.tar.gz tp> cd rubygems-0.8.10 rubygems-0.8.10> sudo ruby setup.rb Now, use RubyGems to install Rails. Issue the following command. tp> sudo gem install rails –include-dependencies The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Mac OS X. NOTE − In case you face any problem with above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So just issue the following command and you will have everything updated automatically. tp> sudo gem update Then try the above command with updated gems. Rails Installation on Linux 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.6, then skip to step 5. Otherwise, we”ll do a fresh installation for Ruby. Download ruby-x.y.z.tar.gz from www.ruby-lang.org Untar the distribution, and enter the top-level directory. Do the usual open-source build as follows − tp> tar -xzf ruby-x.y.z.tar.gz tp> cd ruby-x.y.z ruby-x.y.z> ./configure ruby-x.y.z> make ruby-x.y.z> make test ruby-x.y.z> make install Install RubyGems. Go to rubygems.rubyforge.org, and follow the download link. Once you have the file locally, enter the following at your command prompt − tp> tar -xzf rubygems-x.y.z.tar.gz tp> cd rubygems-x.y.z rubygems-x.y.z> ruby setup.rb Now use RubyGems to install Rails. Still in the shell, issue the following command. tp> gem install rails –include-dependencies The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Linux. NOTE − In case you face any problem with above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So, just issue the following command and you will have everything updated automatically. tp> sudo gem update Then try the above command with updated gems. Keeping Rails Up-to-Date Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. Issue the following command − tp> gem update rails This will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While giving this command, make sure you are connected to the internet. Installation Verification You can verify if everything is setup according to your requirements or not. Use the following command to create a demo project in Rails environment. tp> rails demo This will create a demo rails” project using SQLite database. Note that Rails uses SQLite as its default database. We can create an application that will use MySQL database. Assuming you have MySQL database setup on your machine, issue the following command to create an application that will use MySQL database − tp> rails -d mysql demo We will discuss the database setup part in subsequent chapters. Currently we have to check if our environment is setup properly or not. Use the following commands to run WEBrick web server on your machine − tp> cd demo demo> ruby script/server => Rails application started on http://0.0.0.0:3000 => Ctrl-C to shutdown server; call with –help

Rails 2.1 Migrations

Ruby on Rails 2.1 – Migrations ”; Previous Next Rails Migration uses Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code. It has many uses, such as − Teams of developers − if one person makes a schema change, the other developers just need to update, and run “rake migrate”. Production servers − run “rake migrate” when you roll out a new release to bring the database up to date as well. Multiple machines − if you develop on both a desktop and a laptop, or in more than one location, migrations can help you keep them all synchronized. What can Rails Migration Do? create_table(name, options) drop_table(name) rename_table(old_name, new_name) add_column(table_name, column_name, type, options) rename_column(table_name, column_name, new_column_name) change_column(table_name, column_name, type, options) remove_column(table_name, column_name) add_index(table_name, column_name, index_type) remove_index(table_name, column_name) Migrations support all the basic data types − string, text, integer, float, date-time, timestamp, time, date, binary and Boolean − string − is for small data types such as a title. text − is for longer pieces of textual data, such as the description. text − is for longer pieces of textual data, such as the description. integer − is for whole numbers. float − is for decimals. date-time and timestamp − stores the date and time into a column. date and time − stores either the date only or time only. binary − is for storing data such as images, audio, or movies. boolean − is for storing true or false values. Valid column options are − limit ( :limit => “50” ) default (:default => “blah” ) null (:null => false implies NOT NULL) NOTE − The activities done by Rails Migration can be done using any front-end GUI or direct on SQL prompt, but Rails Migration makes all those activities very easy See the Rails API for details on these. Create the Migrations Here is the generic syntax for creating a migration − C:rubyapplication> ruby script/generate migration table_name This will create the file db/migrate/001_table_name.rb. A migration file contains basic Ruby syntax that describes the data structure of a database table. NOTE − Before running migration generator, it is recommended to clean the existing migrations generated by model generators. We will create two migrations corresponding to our three tables – books and subjects.. C:ruby> cd library C:rubylibrary> ruby script/generate migration books C:rubylibrary> ruby script/generate migration subjects Notice that you are using lowercase for book and subject and using the plural form while creating migrations. This is a Rails paradigm that you should follow each time you create a Migration. − Edit the Code to Tell it What to Do Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. Modify 001_books.rb as follows − The ID column will be created automatically, so don”t do it here as well. class Books < ActiveRecord::Migration def self.up create_table :books do |t| t.string :title, :limit => 32, :null => false t.float :price t.integer :subject_id t.text :description t.timestamp :created_at end end def self.down drop_table :books end end The method self.up is used when migrating to a new version, self.down is used to roll back any changes if needed. At this moment, the above script will be used to create the books table. Modify 002_subjects.rb as follows − class Subjects < ActiveRecord::Migration def self.up create_table :subjects do |t| t.string :name end Subject.create :name => “Physics” Subject.create :name =>”Mathematics” Subject.create :name => “Chemistry” Subject.create :name => “Psychology” Subject.create :name => “Geography” end def self.down drop_table :subjects end end The above script will be used to create subjects table; it will create five records in the subjects table. Run the Migration Now that you have created all the required migration files, it is time to execute them against the database. To do this, go to the command prompt and open the library directory in which the application is located, and then type rake migrate as follows − C:rubylibrary> rake db:migrate This will create a “schema_info” table if it doesn”t exist, which tracks the current version of the database. Each new migration will be a new version, and any new migrations will be run, until your database is at the current version. Rake is a Ruby build program similar to Unix make program that Rails takes advantage of, to simplify the execution of complex tasks such as updating a database”s structure etc. Running Migrations for Production and Test Databases If you would like to specify what rails environment to use for the migration, use the RAILS_ENV shell variable. For example − C:rubylibrary> set RAILS_ENV=production C:rubylibrary> rake db:migrate C:rubylibrary> set RAILS_ENV=test C:rubylibrary> rake db:migrate C:rubylibrary> set RAILS_ENV=development C:rubylibrary> rake db:migrate NOTE − On Unix, use “export RAILS_ENV=production” instead of set command. What is Next? Now we have our database and the required tables available. In the two subsequent chapters, we will explore two important components called Controller (ActionController) and View (ActionView). Creating Controllers ( Action Controller ) Creating Views ( Action View ) Print Page Previous Next Advertisements ”;

Rails 2.1 Views

Ruby on Rails 2.1 – Views ”; Previous Next A Rails View is an ERb program that shares data with controllers through mutually accessible variables. If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers we have created: book. Each of these subdirectories was created automatically when the same-named controller was created with the generate script. Now, assuming your web server is up and running, provide the following input in your browser”s address box − http://localhost:3000/book/list You get the following error message because you have not defined any view file for any method defined in the controller. Rails lets you know that you need to create the view file for the new method. Each method you define in the controller needs to have a corresponding RHTML file, with the same name as the method, to display the data that the method is collecting. So let us create view files for all the methods we have defined in book_controller.rb. Creating View File for list Method Create a file called list.rhtml using your favorite text editor and save it to app/views/book. After creating and saving the file, refresh your web browser. You should see a blank page; if you don”t, check the spelling of your file and make sure that it is exactly the same as your controller”s method. Now, to display the actual content, let us put the following code into list.rhtml. <% if @books.blank? %> <p>There are not any books currently in the system.</p> <% else %> <p>These are the current books in our system</p> <ul id=”books”> <% @books.each do |c| %> <li><%= link_to c.title, {:action => ”show”, :id => c.id} -%></li> <% end %> </ul> <% end %> <p><%= link_to “Add new Book”, {:action => ”new” }%></p> The code to be executed is to check whether the @books array has any objects in it. The .blank? method returns true if the array is empty, and false if it contains any objects. This @books object was created in controller inside the list method. The code between the <%= %> tags is a link_to method call. The first parameter of link_to is the text to be displayed between the <a> tags. The second parameter is what action is called, when the link is clicked. In this case, it is the show method. The final parameter is the id of the book that is passed via the params object Now, try refreshing your browser and you should get the following screen because we don”t have any book in our library. Creating View File for new Method Till now, we don”t have any book in our library. We have to create a few books in the system. So, let us design a view corresponding to the new method defined in book_controller.rb. Create a file called new.rhtml using your favorite text editor and save it to app/views/book. Add the following code to the new.rhtml file. <h1>Add new book</h1> <% form_tag :action => ”create” do %> <p><label for=”book_title”>Title </label>: <%= text_field ”book”, ”title” %></p> <p><label for=”book_price”>Price</label>: <%= text_field ”book”, ”price” %></p> <p><label for=”book_subject”>Subject</label>: <%= collection_select(:book,:subject_id,@subjects,:id,:name) %></p> <p><label for=”book_description”>Description</label><br/> <%= text_area ”book”, ”description” %></p> <%= submit_tag “Create” %> <% end %> <%= link_to ”Back”, {:action => ”list”} %> Here the start_form_tag() method interprets the Ruby code into a regular HTML <form> tag using all the information supplied to it. This tag, for example, outputs the following HTML − <form action=”/book/create” method=”post”> The next method is text_field that outputs an <input> text field. The parameters for text_field are object and field name. In this case, the object is book and the name is title. The Rails method called collection_select creates an HTML select menu built from an array, such as the @books one. There are five parameters, which are as follows − :book − The object you are manipulating. In this case, it”s a book object. :subject_id − The field that is populated when the book is saved. @books − The array you are working with. :id − The value that is stored in the database. In terms of HTML, this is the <option> tag”s value parameter. :name − The output that the user sees in the pull-down menu. This is the value between the <option> tags. The next used is submit_tag, which outputs an <input> button that submits the form. Finally, there is the end_form_tag method that simply translates into </form>. Go to your browser and visit http://localhost:3000/book/new. This will give you the following screen. Enter some data in this form and then click the Create button. This will result in a call to create method, which does not need any view because this method is using either the list or new methods to view the results. When you click the Create button, the data should submit successfully and redirect you to the list page, in which you now have a single item listed as follows − If you click the link, you should see another error “Template is missing” since you haven”t created the template file for the show method yet. Creating View File for show Method This method will display the complete detail about any book available in the library. Create a show.rhtml file under app/views/book and populate it with the following code − <h1><%= @book.title %></h1> <p> <strong>Price: </strong> $<%= @book.price %><br /> <strong>Subject :</strong> <%= @book.subject.name %><br /> <strong>Created Date:</strong> <%= @book.created_at %><br /> </p> <p><%= @book.description %></p> <hr /> <%= link_to ”Back”, {:action => ”list”} %> This is the first time you have taken full advantage of associations, which enable you to easily pull data from related objects. The format used is @variable.relatedObject.column. In this instance, you can pull the subject”s name value through the @book variable using the belongs_to associations. If you click on any listed record, it will show you the following screen. Creating View File for edit Method Create a new file called edit.rhtml and save it in app/views/book. Populate it with the

Rails 2.1 Unit Testing

Ruby on Rails 2.1 – Unit Testing ”; Previous Next Introduction Before proceeding, let”s have a quick look at a few definitions − The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application. The Assertion − This is a one line of code that evaluates an object (or expression) for expected results. For example – Is this value = that value? Is this object nil? The Test Case − This is a class inherited from Test::Unit::TestCase containing a testing strategy comprised of contextually related tests. The Test Suite − This is a collection of test cases. When you run a test suite, it will, in turn, execute each test that belongs to it. Rails Testing When you run the helper script script/generate to create controllers and models, Rails generate a framework for unit and functional tests. You can get pretty good test coverage by filling in the framework with tests for the functionality you write. There are two important points to test in a Rails application − Testing the Models Testing the Controllers This tutorial will cover both the testings in brief. So let”s create one testapp to understand the concept. C:ruby> rails -d mysql testapp Database Setup Till now, we have used only Rails application”s development database, but now you need to make sure that the testing database is also created and appropriate sections of your config/database.yml file are set up correctly. Let”s create development and testing databases as follows − mysql> create database testapp_test; Query OK, 1 row affected (0.01 sec) mysql> create database testapp_development; Query OK, 1 row affected (0.01 sec) mysql> use testapp_test; Database changed mysql> grant all privileges on testapp_test.* to ”root”@”localhost” identified by ”password”; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) Configuring database.yml Configure your config/database.yml as follows − development: adapter: mysql encoding: utf8 database: testapp_development username: root password: password host: localhost test: adapter: mysql encoding: utf8 database: testapp_test username: root password: password host: localhost production: adapter: mysql encoding: utf8 database: testapp_production username: root password: password host: localhost Generate Migration Assume you have a table containing books, including their titles, price, and a small description. The following migration sets up this table − testapp > ruby script/generate migration books Now modify the testapp/db/migrate/20080616170315_books.rb file as follows − class Books < ActiveRecord::Migration def self.up create_table :books do |t| t.string :title, :limit => 32, :null => false t.float :price t.text :description t.timestamp :created_at end end def self.down drop_table :books end end Now run the migration as follows − testapp > rake db:migrate This will create books table in testapp_development database. Thereafter, we need to set up your test database using rake command as follows − C:rubytestapp > rake db:test:clone_structure This will clone the testapp_development database into testapp_test database. It means whatever you have in the development database, now you will have the same data in the test database as well. Testing Models When you generate a model with the generate script, Rails also generates a unit test script for the model in the test directory. It also creates a fixture, a YAML file containing test data to be loaded into the testapp_test database. This is the data against which your unit tests will run − testapp > ruby script/generate model Book exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/book.rb create test/unit/book_test.rb create test/fixtures/books.yml create db/migrate create db/migrate/20080616164236_create_books.rb As you write code in the model classes, you”ll write corresponding tests in these files. So let”s create two test book records using YAML in test/fixtures/books.yml as follows − perl_cb: id: 1 title: ”Ruby Tutorial” price: 102.00 description : ”This is a nice Ruby tutorial” java_cb: id: 2 title: ”Java Programming” price: 62.00 description : ”Java Programming for the beginners” Now let”s replace the existing code in book unit test file test/unit/book_test.rb with the following code − require File.dirname(__FILE__) + ”/../test_helper” class BookTest < ActiveSupport::TestCase fixtures :books def test_book perl_book = Book.new :title => books(:perl_cb).title, :price => books(:perl_cb).price, :description => books(:perl_cb).description, :created_at => books(:perl_cb).created_at assert perl_book.save perl_book_copy = Book.find(perl_book.id) assert_equal perl_book.title, perl_book_copy.title perl_book.title = “Ruby Tutorial” assert perl_book.save assert perl_book.destroy end end Finally, run the test method as follows − testapp > ruby test/unit/book_test.rb Here”s the output of running the successful test case − testapp > ruby test/unit/book_test_crud.rb Loaded suite ./test/unit/book_test Started . Finished in 0.0625 seconds. 1 tests, 4 assertions, 0 failures, 0 errors Let’s analyze what happened here − The BookTest method starts off by creating a new Book object using the title and other fields from the first record in the text fixture/books.yml. The resulting object is stored in the perl_book instance variable. The first assertion tests that saving the Book object was successful. Next, the book object is retrieved using the find method and stored in another instance variable named perl_book_copy. The success of this retrieval is tested in the next assertion, which compares the titles of both book objects. At this point, we”ve tested the ability to create and read a database record. The solution tests updating by assigning a new title to the object stored in perl_book and then asserts that saving the change is successful. Finally, the ability to destroy a Book object is tested. This is how we can test our Rails Models. Testing the Controllers Controller testing is also known as functional testing. Functional testing tests the following type of functionalities of the controllers − Is the response redirected as expected? Is the expected template rendered? Is the routing as expected? Does the response contain the expected tags? Rails framework supports five types of requests − get post put head delete To write a functional test, you need to simulate any of the five HTTP request types that your controller will process. Request type “get” and “post” are the most commonly used in controller testing. All these methods take four arguments − The action

Rails 2.1 Routes System

Ruby on Rails 2.1 – Routes System ”; Previous Next Rails parses the URL to determine the controller, action, and parameters for the request. With Rails routing, parts of the URL can specify additional parameters, and the entire routing process is under your control. Routing rules work the same on any web server. The config/routes.rb file is at the heart of the Rails routing system. This file contains rules that try to match the URL path of a request and determine where to direct that request. The rules are tested in the order they are defined in the file. The first rule to match a request”s URL path determines the fate of that request. The routing system actually does two things − It maps requests to action methods inside the controllers. It writes URLs for you for use as arguments to methods like link_to, redirect_to, and form_tag. Thus, the routing system knows how to turn a visitor”s request URL into a controller/action sequence. It also knows how to manufacture URL strings based on your specifications. Consider the following route installed by Rails when you generate your application − map.connect ”:controller/:action/:id” This route states that it expects requests to consist of a :controller followed by an :action that in turn is fed some :id. If you get an incoming request for “http://localhost:3000/book/edit/2”, then it will map as follows − params = { :controller => ”book”, :action => ”edit”, :id => ”2” } Thus the default routing (if you don”t modify the routing rules) is − http://<base-url>/<controller>/<action>/<id> A URL like http://www.example.com/book/update/20 calls the update method (the action) in the BooksController class (the controller) with an id parameter set to the value 20. The following code block will set up book as the default controller if no other is specified. It means visiting ”/” would invoke the book controller. ActionController::Routing:Routes.draw do |map| map.connect ”:controller/:action/:id”,:controller => ”book” end You can also define a default action if no action is specified in the given URL − ActionController::Routing:Routes.draw do |map| map.connect ”:controller/:action/:id”, :action => ”edit”,:controller => ”book” end Now, you can all edit methods inside the book controller to edit book with ID as 20 as follows − http://localhost:3000/2 Route Priority Routes have priority defined by the order of appearance of the routes in the routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority and will be applied last. If no route matches, 404 is returned. Modifying the Default Route You can change the default route as per your requirement. In the following example, we are going to interchange controller and action as follows − # Install the default route as the lowest priority. map.connect ”:action/:controller/:id” Now, to call action from the given controller, you would have to write your URL as follows − http://localhost:3000/action/controller/id It”s not particularly logical to put action and controller in such sequence. The original default (the default default) route is better and recommended. The Ante-Default Route The ”ante-default” route looks as follows − map.connect ”:controller/:action/:id.:format” The .:format at the end matches a literal dot and a wildcard “format” value after the id field. That means it will match, for example, a URL like this − http://localhost:3000/book/show/3.xml Here, inside the controller action, your params[:format] will be set to xml. The Empty Route The empty route is sort of the opposite of the default route. In a newly generated routes.rb file, the empty route is commented out, because there”s no universal or reasonable default for it. You need to decide what this nothing URL should do for each application you write. Here are some examples of fairly common empty route rules − map.connect ””, :controller => “main”, :action => “welcome” map.connect ””, :controller => “main” Here is the explanation of the above rules − The first one will search for welcome action inside main controller even if you type just http://localhost:3000. That last one will connect to http://localhost:3000/main/index. Here index is the default action when there”s none specified. Rails 2.0 introduces a mapper method named root which becomes the proper way to define the empty route for a Rails application, like this − map.root :controller => “homepage” Defining the empty route gives people something to look at when they connect to your site with nothing but the domain name. Named Routes As you continue developing your application, you will probably have a few links that you use throughout your application. For example, you will probably often be putting a link back to the main listings page. Instead of having to add the following line throughout your application, you can instead create a named route that enables you to link to a shorthand version of that link − link_to ”Home”, :controller => ”classified”, :action => ”list” You can define named routes as follows. Here instead of using connect, you are using a unique name that you can define. In this case, the route is called home. The rest of the route looks similar to the others you have created. map.home ””, :controller => ”classified”, :action => ”list” Now, you can use this in the controllers or views as follows − <%= link_to ”Back”, home_url %> Here, instead of listing the :controller and :action to which you will be linking, you are instead putting the name of the route followed by _url. Your user shouldn”t notice any difference. Named routing is merely a convenience for the Rails developer to save some typing. The above case can be written without the named route as follows − <%= link_to ”Back”, {:action => ”list”} %> Pretty URLs Routes can generate pretty URLs. For example − map.connect ”articles/:year/:month/:day”, :controller => ”articles”, :action => ”find_by_date”, :year => /d{4}/, :month => /d{1,2}/, :day => /d{1,2}/ # Using the route above, the url below maps to: # params = {:year => ”2005”, :month => ”11”, :day => ”06”} # http://localhost:3000/articles/2005/11/06 To obtain more detail on Routes, please go through ActionController::Routing. Print Page

Rails 2.1 Sends Emails

Ruby on Rails 2.1 – Sending Emails ”; Previous Next ActionMailer is the Rails component that enables applications to send and receive emails. In this chapter, we will see how to send an email using Rails. Let’s start with creating an emails project using the following command. C:ruby> rails -d mysql emails Here we are using -d mysql option to specify our interest to use MySQL database. We can specify any other database name like oracle or postgress using the -d option. By default, Rails uses SQLite database. Setting Up the Database Even though we are not using a database in our application, but Rails needs it to proceed. So let”s perform these additional steps. Given below is the way to create a database − mysql> create database emails; Query OK, 1 row affected (0.01 sec) mysql> grant all privileges on emails.* to ”root”@”localhost” identified by ”password”; Query OK, 0 rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec) To direct Rails to locate the database, edit the configuration file ~uploadconfigdatabase.yml and change the database name to cookbook. When you finish, it should look as follows − development: adapter: mysql encoding: utf8 database: emails username: root password: password host: localhost test: adapter: mysql encoding: utf8 database: emails username: root password: password host: localhost production: adapter: mysql encoding: utf8 database: emails username: root password: password host: localhost Action Mailer – Configuration Following are the steps you have to follow to complete your configuration before proceeding with the actual work. − Go to the config folder of your emails project and open the environment.rb file and add the following line at the bottom of this file. ActionMailer::Base.delivery_method = :smtp It informs the ActionMailer that you want to use the SMTP server. You can also set it as :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux. Add the following lines of code at the bottom of your environment.rb as well. ActionMailer::Base.smtp_settings = { :address => “smtp.tutorialspoint.com”, :port => 25, :domain => “tutorialspoint.com”, :authentication => :login, :user_name => “username”, :password => “password”, } Replace each hash value with proper settings for your Simple Mail Transfer Protocol (SMTP) server. You can take this information from your Internet Service Provider if you already don”t know. You don”t need to change port number 25 and authentication type if you are using standard SMTP server. You may also change the default email message format. If you prefer to send email in HTML instead of plain text format, add the following line to config/environment.rb as well − ActionMailer::Base.default_content_type = “text/html” ActionMailer::Base.default_content_type could be set to “text/plain”, “text/html”, and “text/enriched”. The default value is “text/plain”. The next step is to create a mailer. Generate a Mailer Use the following command to generate a mailer as follows − C:ruby> cd emails C:rubyemails> ruby script/generate mailer Emailer It will create a file emailer.rb in the app/models directory. Check the content of this file as follows − class Emailer < ActionMailer::Base end Now let”s create one method inside the ActionMailer::Base class as follows − class Emailer < ActionMailer::Base def contact(recipient, subject, message, sent_at = Time.now) @subject = subject @recipients = recipient @from = ”[email protected]” @sent_on = sent_at @body[“title”] = ”This is title” @body[“email”] = ”[email protected]” @body[“message”] = message @headers = {} end end The contact method has four parameters: a recipient, a subject, a message, and a sent_at, which defines when the email is sent. The method also defines six standard parameters that are a part of every ActionMailer method − @subject defines the e-mail subject. @body is a Ruby hash that contains values with which you can populate the mail template. You created three key-value pairs: title, email, and message @recipients is a list of the people to whom the message is being sent. @from defines who the e-mail is from. @sent_on takes the sent_at parameter and sets the timestamp of the email. @headers is another hash that enables you to modify the e-mail headers. For example, you can set the MIME type of the e-mail if you want to send either plain text or HTML e-mail. Creating the Controller Now, we will create a controller for this application as follows − C:rubyemails> ruby script/generate controller Emailer Let’s define a controller method sendmail in app/controllers/emailer_controller.rb, which will call the Model method to send an actual email as follows − class EmailerController < ApplicationController def sendmail recipient = params[:email] subject = params[:subject] message = params[:message] Emailer.deliver_contact(recipient, subject, message) return if request.xhr? render :text => ”Message sent successfully” end end To deliver e-mail using the mailer”s contact method, you have to add deliver_ to the beginning of the method name. You add a return if request.xhr?, so that you can escape to Rails Java Script (RJS) if the browser does not support JavaScript and then instruct the method to render a text message. You are almost done except to prepare a screen from where you will get the user information to send email. Let”s define one screen method index in the controller and then in the next section, we will define all the required views − Add the following code in emailer_controller.rb file. def index render :file => ”appviewsemailerindex.html.erb” end Defining Views Define a view in appviewsemailsindex.html.erb. This will be called as the default page for the application and will allow users to enter message and send the required email − <h1>Send Email</h1> <% form_tag :action => ”sendmail” do %> <p><label for=”email_subject”>Subject</label>: <%= text_field ”email”, ”subject” %></p> <p><label for=”email_recipient”>Recipient</label>: <%= text_field ”email”, ”recipient” %></p> <p><label for=”email_message”>Message</label><br/> <%= text_area ”email”, ”message” %></p> <%= submit_tag “Send” %> <% end %> Apart from the above view, we need one more template, which will be used by the Emailer”s contact method while sending message. This is just text with standard Rails <%= %> placeholders scattered throughout. Just put the following code in the app/views/contact.html.erb file. Hi! You are having one email message from <%= @email %> with a title <%= @title

Rails 2.1 Dir Structure

Ruby on Rails 2.1 – Dir Structure ”; Previous Next When you use the helper script of Rails to create your application, it creates the entire directory structure for your application. Rails knows where to find things it needs within this structure, so you don”t have to provide any input. Here is a top-level view of the directory tree created by the helper script at the time of an application creation. Except for minor changes between the 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 re-learning the project”s organization. To understand this directory structure, let”s use the demo application created in the installation chapter. This can be created using a simple helper command as follows − C:ruby> rails -d mysql demo Now, go into the demo application root directory as follows − C:ruby> cd demo C:rubydemo> dir You will find a directory structure as follows − demo/ …./app ……../controller ……../helpers ……../models ……../views …………../layouts …./config …./db …./doc …./lib …./log …./public …./script …./test …./tmp …./vendor README Rakefile Now let”s explain the purpose of each directory. app − It 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. It 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 app/view/layouts − Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default </tt> and create a file named default.rhtml. Inside default.erb, call <% yield %> to render the view using this layout. config − This directory contains a 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. doc − This directory is where your application documentation will be stored when generated using rake doc:app. lib − Application-specific libraries go here. Basically, any kind of custom code that doesn”t belong under controllers, models, or helpers. This directory is in the load path. log − Error logs go here. Rails creates scripts that help you manage various error logs. You”ll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log). public − Like the public directory for a web server, this directory has web files that don”t change, such as JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public). This should be set as the DOCUMENT_ROOT of your web server. script − This directory holds scripts to launch and manage the various tools that you”ll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server), etc. test − The tests you write and those Rails creates for you, all goes here. You”ll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional). tmp − Rails uses this directory to hold temporary files for intermediate processing. vendor − Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) goes here. Apart from these directories, there will be two files available in the demo directory. README − This file contains a basic detail about Rail Application and description of the directory structure explained above. Rakefile − This file is similar to Unix Makefile, which helps in building, packaging, and testing the Rails code. This will be used by rake utility supplied along with Ruby installation. Print Page Previous Next Advertisements ”;

Rails 2.1 Examples

Ruby on Rails 2.1 – Examples ”; Previous Next Subsequent chapters are based on the example taken in this chapter. In this chapter, we will create a simple but operational online library system for holding and managing the books. This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored in your database − Books − They describe an actual listing of the books. Subject − This is used to group books together. Workflow for Creating Rails Applications A recommended workflow for creating a Rails Application is as follows − Use the rails command to create the basic skeleton of the application. Create a database with necessary definition in the MySQL server to hold your data. Configure the application to know where your database is located and specify the login credentials for it. Create Rails Active Records (Models), because they are the business objects you”ll be working with in your controllers. Generate Migrations that simplify the creating and maintaining of database tables and columns. Write Controller Code to put a life in your application. Create Views to present your data through User Interface. So, let us start with creating our library application. Creating an Empty Rails 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. Go to ruby installation directory to create your application. Run the following command to create a skeleton for our library application. C:ruby> rails -d mysql library 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. Check Rails Directory Structure for more detail. Here, we are using -d mysql option to specify our interest to use MySQL database. We can specify any other database name like oracle or postgress using -d option. By default, Rails uses SQLite database. Most of our development work will be creating and editing files in the ~/library/app subdirectories. Here”s a quick rundown on how to use them − The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user. 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. The models subdirectory holds the classes that model and wrap the data stored in our application”s database. In the most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple. 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. Starting Web Server Rails web application can run virtually under any web server, but the most convenient way to develop and test a Rails web application is to use the built-in WEBrick web server. Let”s start this web server and then browse to our empty library application. This server will be started from the application directory as follows. It runs on port number 3000 − C:> cd rubylibrary C:rubylibrary> ruby script/server It will start your WEBrick web server listening for Web Requests at port number 3000 at local machine. Now open your browser and browse to http://127.0.0.1:3000. If everything goes fine, then you should see a greeting message from WEBrick. Following is the screen for a successful setup − If you do not get a greeting message as above, it means there is something wrong with your setup and you need to fix it before proceeding ahead. What is Next? The next chapter explains how to create databases for your application and what is the configuration required to access these created databases. Further, we will see what is Rail Migration and how it is used to maintain database tables. Print Page Previous Next Advertisements ”;