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 ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.