So far, it\’s RoR

Ruby on Rails, PostgreSQL, SVN, etc….

What exactly does the scaffold_resource generator give you?

Posted by Chirag Patel on September 25, 2007

The regular scaffold generator (e.g. ruby script/generate scaffold model controller) requires you to create your model and controller first. The scaffold_resource generator, on the other hand, generates the (RESTful) model and controller for you. For example:

ruby script/generate scaffold_resource Caregiver first_name:string last_name:string

In Rails 2.0, use resource instead:

ruby script/generate scaffold Caregiver first_name:string last_name:string

Here’s everything you get:

Views for all the CRUD operations and a layout

create app/views/caregivers/index.rhtml

create app/views/caregivers/show.rhtml

create app/views/caregivers/new.rhtml

create app/views/caregivers/edit.rhtml

create app/views/layouts/caregivers.rhtml


create app/models/caregiver.rb

Controller with methods for CRUD operations

create app/controllers/caregivers_controller.rb


create app/helpers/caregivers_helper.rb

Looks like this initially

module CaregiversHelper


Migration to create the table in the database

create db/migrate/003_create_caregivers.rb

Looks like this:

class CreateCaregivers < ActiveRecord::Migration

  def self.up

    create_table :caregivers do |t|

      t.column :first_name, :string

      t.column :last_name, :string

      t.column :address, :string

      t.column :city, :string

      t.column :state, :string

      t.column :home_phone, :string

      t.column :work_phone, :string

      t.column :cell_phone, :string

      t.column :relationship, :string

      t.column :email, :string


  end  def self.down

    drop_table :caregivers



Sets up route in config/routes.rb for REST

map.resources :caregivers


Posted in Ruby on Rails | 1 Comment »

Passing parameters to partials

Posted by Chirag Patel on September 12, 2007

Partial basics

Some different things about passing parameters to partials

  1. Basics of passing parameters (i.e. locals) into partials – Why are parameters for partials (locals) passed differently than params for urls?!? Don’t know, but basically use the locals hash in both the render call and use the name of the local in the partial itself. This link also shows how to explicitly check for local parameter in case it’s nil
  2. Making a partial use optional parameters – Basically, set the parameter to nil inside the partial (e.g. title = nil unless defined?(title))
  3. Why passing locals in partials is preferred over @variables – Partials can see the @variables of its parent view, but instead pass the variables as parameters for clarity in complex code bases

Debugging partials

  1. be sure to look at console log (and/or development log), it will show the parameters being passed

Posted in Ruby on Rails | Leave a Comment »

Dynamic styles with HTML, CSS, and Javascript

Posted by Chirag Patel on September 12, 2007

Styles can be dynamically changed in 4 ways:

  • With Javascript (overrides all other styles)

    el = document.getElementById('pageBody'); = 'red';

  • Inline styles (override both embedded and external styles)

    Inline styles are styles that are written directly in the tag on the document. Inline styles affect only the tag they are applied to.

<a href="" style="font-size:91%;">

  • Embedded styles (overrides external styles)

    Embedded styles are styles that are embedded in the head of the document. Embedded styles affect only the tags on the page they are embedded in.

<style type="text/css">
body { color: #FFFFFF; }

  • External styles (.css page)

    External styles are styles that are written in a separate document and then attached to various Web documents. External style sheets can affect any document they are attached to.

<link rel="stylesheet" type="text/css" href="layout.css" />

Posted in HTML/CSS, Javascript | Leave a Comment »

Setting up BackgroundDrb

Posted by Chirag Patel on September 12, 2007

I decided to use BackgrounDrb 0.2.1 to launch a periodic task that would run every 15 seconds.Warning: After going through the hassle of setting up BackgrounDrb, I found out that it isn’t even supported in Windows (my dev environment)! See step 8. So, these instructions haven’t been fully tested yet on a *.nix environment. Good luck and please post comments if you have any helpful suggestions.

  1. Install BackgroundDrb: svn co backgroundrb
  2. Setup BackgroundDrb: rake backgroundrb:setup
  3. Generate worker thread (Foo is capitalized): ruby script/generate worker Foo
  4. In one of your controllers, create new worker with Middleman object (:foo_worker is lowercase with underscore)
       MiddleMan.new_worker(:class => :foo_worker,
        :args => "Arguments used to instantiate a new HeartratepostWorker object",
  5. Instantiate Middleman object in environment.rb (you might not need this with version 0.2.1 of BackgrounDrb)
      require "drb"  DRb.start_service
      MiddleMan =, "druby://localhost:22222"
  6. Install the daemons gem if you haven’t already: gem install daemons
  7. Install the slave gem if you haven’t already: gem install slave
  8. Start the BackgroundDrb server in a separate command window: ruby script\backgroundrb start
    • If you get the error “ERROR: there is already one or more instance(s) of the program running”, delete log\
    • Windows users are out of luck! You’ll get this message: `fork': the fork() function is unimplemented on this machine. Here’s a message from Ezra (the devleoper of BackgroundDrb) about Windows support:
      • “Unfortunately that won’t cut it in this case, I wish it would. Slave does more then just fork. It uses ipc and a few other things that just don’t work yet on windows. There is a possibility it could be made to work but right now it does not, even with win32 process (gem). -Ezra Wed Nov 29 16:19:03 EST 2006”
  9. Debugging methods if things don’t work well


  1. You might want to restart the backgroundrb server after you’ve modified the *_worker.rb file to lib/workers. It could cause an error otherwise.
  2. In case you get this error when starting Mongel, copy the vendor/plugins/backgroundrb directory to a temp directory and it will work

    already initialized constant OPTIONS

  3. To set up a periodic task, set up the Middleman object this way:
            session[:job_key] = worker
              :class => :heartrate_post_worker,
              :args => "some arg to do_work",
              :job_key => :simple_schedule,
              :trigger_args => {
                :start =>,
                :end => + 10.minutes,
                :repeat_interval => 15.seconds


  1. Sending emails in the background with ActionMailer and BackgrounDRB
  2. Example using TTL (time to live)

Posted in Ruby on Rails | 2 Comments »

Accessing your application classes (including models) in Rake tasks

Posted by Chirag Patel on September 1, 2007

When writing Rake tasks, to get access to all classes (such as the User model in this example) in your app’s environment, you need to depend on the :environment task shown as follows:

  task :post_user => :environment  do
    end_time =
    start_time = end_time - 60 #subtract 60 seconds
    until start_time > end_time
      start_time = start_time + 15 #increment 15 seconds
      puts "Posting #{start_time}"
      uesr = => 817, :timestamp => start_time)

Posted in Ruby on Rails | Leave a Comment »

Making (and verifying) the migration to PostgreSQL in Rails

Posted by Chirag Patel on August 20, 2007


After installing PostgreSQL on Windows, I converted my Rails application from MySQL to PostgreSQL with the following steps:

  1. Create a new database in PostgreSQL
  2. Installed postgres-pr gem (Ruby driver) because the postgres gem (native driver) didn’t work. Will figure out why later on.
  3. Changed the appropriate Rails config stuff in database.yml
      adapter: postgresql
      database: database_name
      username: postgres
      password: password
      host: localhost
  4. I ran only my first Rails migration to test that it worked using this command: rake db:migrate VERSION=1. My first migration (001_create_heartrates.rb) creates a table in the database so it will be easy to test.

Robby explains a quick way to migrate the data as well


You can test that the migration worked via 2 methods (GUI or command line)

  1. Using following commands with the psql command line utility (Start Menu -> PostgreSQL -> psql to postgres):
    psql commmand Description
    \? help
    \c database_name connect to a database (many other commands won’t work until you execute this)
    \dt show tables (execute \c first)
    \d table_name describes a particular table (e.g. table_name)
  2. Using the pgAdmin III GUI:
    • The database table is deeply nested in the tree, I missed it at first. Go to PostgreSQL Database Server 8.2 -> Databases -> database_name -> Schemas -> public -> Tables -> table_name

Posted in PostgreSQL, Ruby on Rails | Leave a Comment »

Settings for creating a new database in PostgreSQL

Posted by Chirag Patel on August 20, 2007

I wanted to quickly create a new database via pgAdmin III, so I used the following properties

Note: initdb (which ran during step 6 of the installation process) creates two initial databases, namely postgres and template1. Also, the cluster created by initdb also comes with two templates (template0 and template1). template0 is a backup for template1.

Setting Value Description
Owner: postgres I assume postgres refers to the database superuser, not the Windows login.
Encoding: UTF8 Because a PostgreSQL dialog box suggested it would be most flexible in case other clients decided to access the data (instead of SQL_ASCII)
Template: template1 schema extensions and objects are usually loaded into template1
Tablespace: pg_default The pg_default tablespace is the default tablespace of the template1 and template0 databases (and, therefore, will be the default tablespace for other databases as well, unless overridden by a TABLESPACE clause in CREATE DATABASE).Tablespaces in PostgreSQL allow database administrators to define locations in the file system where the files representing database objects can be stored. Two tablespaces are automatically created by initdb .

  1. The pg_global tablespace is used for shared system catalogs.
  2. The pg_default (described above)

One of the things that the tablespace defines is the file path for the data as shown with this command: CREATE TABLESPACE fastspace LOCATION '/mnt/sda1/postgresql/data';

Posted in PostgreSQL | 3 Comments »

Database scaling terminology

Posted by Chirag Patel on August 16, 2007

Some quick explanations on designing scalable databases (thanks to Jon Sime of the PostgreSQL mailing list and Media Matters for America)

Horizontal vs Vertical scaling

Horizontal scaling is merely a general concept which, in its simplest form, means “adding more nodes” as opposed to vertical scaling which (very roughly) means making an individual node as powerful as possible. The two are not mutually exclusive (you could add more nodes, and make each one as powerful as possible — if you’ve got the money), and the concept is not limited to databases.

Horizontal scaling: 3 types of “clustering”

  1. Partitioning (most likely pretty relevant when talking about terabytes of data) is a feature which stores the actual data of a logical table into any number of physical tables (within the same database), each of which store an explicitly defined subset of the data.
    • Note: Partitioning is referred to as clustering in O’Relly’s Building Scalable Web Sites. The book also refers to clustering and federation as types of partitioning. In other words, the terms partitioning and clustering are interchanged.
  2. Federation typically refers to a situation where you have multiple datastores (which can be different databases on one machine, entirely different servers, various mixtures of storage formats, etc.) which each store and are responsible for subsets of your data, with a middleware layer on top of them that mediates access and updates to the underlying and disparate repositories. A certain software package also uses the term to refer to individual non-local tables stored on a single remote server which are presented as if they were local tables.
  3. Replication generally indicates a setup where data is managed across a set of two or more nodes, each node either storing copies of all the data locally, or at least able to access the non-local portions transparently from another source when necessary. Each node in the cluster should be able to present a consistent version of the entire dataset to connected clients (i.e. if you connect to two different nodes and issue the same query at the same time to each, you would get the same data back from both). The issue of propagating all changes to the data from one node to all others in a fail-safe and consistent way makes replication generally very complicated. Specifically in the context of an index, replication can also mean ordering the data in a table based on the values of an indexed column.
    • Note: Replication was originally referred to as clustering by Jon Sime

If anyone has an disagreement (or agreement) of these term’s please leave a comment. I would love to hear your feedback!

Posted in Database | 1 Comment »

Installing PostgreSQL on Windows Vista

Posted by Chirag Patel on August 15, 2007

Just a few notes to be very careful when installing PostgreSQL 8.2.4 on Windows Vista:

Because PostgreSQL needs to be installed as a Windows service, it needs to create an account that will be granted Logon On as a Service permission. When I first installed it, I allowed the installation wizard to use a default account name (postgres) and it generated a password for me. The password was extremely long (25 random chars) and difficult to remember, and for that matter, I could not copy and paste their auto-generated password from the the dialog box that came up. It installed successfully, but when I tried to change the password with the GUI (pgAdmin III), it was unsuccessful. So, I uninstalled PostgreSQL and re-installed it with my own Windows login (instead of the default postgres account) and that’s when things went terribly wrong. After that point, the PostgreSQL would not allow me to reinstall (Error message: “another installation in process”) and on top of that Windows would not allow me to delete the files manually because of permissions rights on the C:\Program Files\PostgreSQL directory. I finally had to do a System Restore and got it working.

To summarize:

  1. Do not use a member of the local administrators group as your Windows login for the service (such as your own personal Windows login) in step 5 of the installation guide!! Using their default postgres is the easiest. But use your own password instead of an autogenerated one. The FAQ (topic 2.3) explains why a non-administrator account is needed for security reasons. By the way, you can start and stop the PostgreSQL service within the Services control panel and also from the PostgreSQL group under the Start Menu.
  2. I would go ahead and allow it to create a database cluster in step 6 of the installation guide. I used the HTTP port number they suggested (5432) and allowed only localhost to access the database. In this step, the account name is the superuser (i.e. root access) of the database cluster.
    Here’s PostgreSQL’s explanation of a database cluster:

    Before you can do anything, you must initialize a database storage area on disk. We call this a database cluster. (SQL uses the term catalog cluster.) A database cluster is a collection of databases that is managed by a single instance of a running database server. After initialization, a database cluster will contain a database named postgres, which is meant as a default database for use by utilities, users and third party applications. The database server itself does not require the postgres database to exist, but many external utility programs assume it exists.

  3. After I successfully installed PostgreSQL, I used these settings to create a new database

Last, see the FAQ for the installation process for further explanations.

Posted in PostgreSQL, Windows | 1 Comment »

Google web history and Google reader

Posted by Chirag Patel on August 15, 2007

In case you’re not using it already, Google’s web history is a free and handy way to find useful links that you forgot to bookmark. I use it quite a bit when when I google search bugs and installation problems that I need to look up later. It can keep track of (1) all of your Google web searches and links you visited from those searches, and optionally (2) all of your web history (not just Google searches)

Click this thumbnail for a screenshot:


It includes a calendar, that you might help you remember what day you need to be looking at.

Also, I prefer Google Reader over Bloglines mainly because of how quick it is to star RSS feeds and tag RSS feeds by keywords. Everything loads quicker in general. Also, keep an eye on, which will allow you to comment the RSS feeds

Please post comments if you know of better alternatives to both tools..

Posted in Other Tools | Leave a Comment »