O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.2. Adding Comments

Your visitors should be able to read articles and comment on them. The information that you need from each commenter is their name, their email address (which you won't display), and the body of their comment. Let's create a new resource for this.

Go ahead and run the following:

C:\projects\blog> ruby script/generate scaffold comment article:references
name:string email:string body:text

This is analogous to what you already did before for the article resource. The only part warranting explanation is article:references. It indicates that you need a foreign key that references the primary key of the articles table so that you can establish a one-to-many relationship between the articles table and the comments table. The foreign key in the comments table will be article_id. It will be an integer (just as the referenced id is).

references has an alias called belongs_to. Using article:belongs_to would have been acceptable as well.

The migration file looks like this:

class CreateComments < ActiveRecord::Migration
  def self.up
    create_table :comments do |t|
      t.references :article
      t.string :name
      t.string :email
      t.text :body

      t.timestamps
    end
  end

  def self.down
    drop_table :comments
  end
end

It is usually a very good idea to add indexes to foreign key columns. This can drastically improve performance. Before proceeding with the creation of the table, you should modify the migration file to add an index as shown here:

class CreateComments < ActiveRecord::Migration def self.up ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required