Skip to content

Instantly share code, notes, and snippets.

@dtuite
Created May 28, 2012 09:42
Show Gist options
  • Save dtuite/2818210 to your computer and use it in GitHub Desktop.
Save dtuite/2818210 to your computer and use it in GitHub Desktop.
Fancy Rails Migrations

Add Indices and Limits

rails g model User name:index email:uniq token:string{6} age:integer
  • name:index creates an indexed column called name.
  • email:uniq creates column called email with a unique index.
  • Specifying token:string{6} constrains the length of token to 6 chars.
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :token, :limit => 6
      t.age :integer

      t.timestamps
    end
    add_index :users, :name
    add_index :users, :email, :unique => true
  end
end

Add Foreign Keys

rails g model Item name user:references
  • Columns default to type string by default.
  • Foreign keys are added (with indices) by specifying references.
class CreateItems < ActiveRecord::Migration
  def change
    create_table :items do |t|
      t.string :name
      t.integer :user_id

      t.timestamps
    end
    add_index :items, :user_id
  end
end

Source: 10 Things You Didn't Know Rails Could do by @jeg2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment