Rails - Quick migration example

Let's assume that we want to add friendly_name field to the bookmark_categories table.

Let's create new migration:

$  rails generate migration add_friendly_url_to_bookmark_categories

Next we need to edit migration file (just look at comments):

class AddFriendlyUrlToBookmarkCategories < ActiveRecord::Migration
  def self.up
    # add friendly_name field to bookmark_categories table
    # we cannot forbid null yet
    add_column :bookmark_categories, :friendly_name, :string, :limit => '32', :unique => true
  
    # update friendly_name for each category
    BookmarkCategory.find(:all).each do |category|
     category.friendly_name = category.name.parameterize
     category.save
    end

    # finally forbid null values
    change_column :bookmark_categories, :friendly_name, :string, :limit => '32', :null => false, :unique => true
  end

  def self.down
    # just remove this column on downgrade
    remove_column :bookmark_categories, :friendly_name
  end
end

Execute migration:

$ rake db:migrate
(in /home/milosz/pim)
==  AddFriendlyUrlToBookmarkCategories: migrating =============================
-- add_column(:bookmark_categories, :friendly_name, :string, {:limit=>"32", :unique=>true})
   -> 0.0029s
-- change_column(:bookmark_categories, :friendly_name, :string, {:limit=>"32", :null=>false, :unique=>true})
   -> 0.1297s
==  AddFriendlyUrlToBookmarkCategories: migrated (1.1918s) ====================
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a system administrator working for a successful Polish company and a long time supporter of Free Software Foundation and Debian operating system.

Gdansk, Poland https://sleeplessbeastie.eu