Ruby on Rails/Examples

This section is a collection of useful Rails examples.

important note
rails command now start with "rails" and not "script/"

How to Add a New Table
script/generate model  Generate the empty model and migration file.

vi db/migrate/XXX_create_.rb Add columns to the table.

rake db:migrate Migrates the data level - that is - creates the new database table.

vi app/models/.rb Define the validations, sizes, etc.

vi test/unit/_test.rb Define the unit tests that exercises the model validations.

If there will be a controller (and views) associated with this Model: script/generate controller    ... Creates the controller and creates a view for each action.

Find
The find method of ActiveRecord is documented in the Rails API manual

Find record by id (an integer). Note: Returns one object. pet_id should be primary number.

- returns the first matching record. [Note: Returns one object.]

- find all records with a given field value. [Notes: 1. Returns an array of objects. Check for no records found with: pets.empty?. 2.:conditions => supplies an SQL fragment used with WHERE *]

- find all records matching multiple field values. [Note: OR also works.]

- find all records matching a pattern. Wild cards are %</tt> for zero or more of any character, and <tt>_</tt> for any single character. To escape a wild card use <tt>\%</tt> or <tt>\_</tt>. The reference from MySQL for LIKE will help. On the MySQL Regex website you will find examples for using REGEX.

- find everything and sort result by name.

- returns no more than the number of rows specified by :limit.

- uses offset to skip the first 50 rows.

Migrations
- migrate to latest level by executing scripts in <tt> /db/migrate</tt>. Note: Migration scripts are created by <tt>script/generate model <mod-name></tt>

Testing
- run all tests.

- run the functional tests, which test the controllers.

- run the unit tests, which test the models.

- run one functional test.

Documentation
- generate Ruby Docs for the application. Docs are placed at <tt> /doc/app/index.html</tt>.

Clean Up
- delete all logs.

- delete temporary files.

Server
- start the web server for this app. By default, the server is running in development mode. By default, it will be accessible at web address: http://localhost:3000/

- start the web server in Test Mode.

- start the web server in Test Mode.

- start the web server in Production Mode (more caching, etc.).

can't convert Fixnum to String
- every Fixnum has method <tt>.to_s</tt> to convert it to a String.

Shell Commands
Certain useful shell commands that I'm always trying to remember:

- run grep, searching for 'hello', on every file in the tree starting with the current directory.

- tar up directory and compress it with gzip.