Pages

Showing posts with label migrations. Show all posts
Showing posts with label migrations. Show all posts

Monday, May 12, 2014

Irreversible Migrations in Ruby on Rails

In Rails 2 in migrations there were only 2 methods: up and down. They are called on running migrations up and down respectively with rake tasks rake db:migrate and rake db:rollback.

In Rails 2

def up
add_column :users, :active, :boolean User.update_all(active: true) end

def down remove_column :users, :active end

Rails 3 produced us great method change which allowed us to write there code which creates a table and drops the table automatically on rolling migration back. But unfortunately there was a problem – you didn’t have opportunity to say “don’t run this peace of code on down but run this only on up”. So the solution was just to use old syntax. 

Saturday, January 4, 2014

Migration to rename an ActiveRecord model and its table in Rails

In Rails 3.1+ ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:
class RenameOldTableToNewTable< ActiveRecord:Migration
    def change
        rename_table :old_table_name, :new_table_name
    end 
 end
You need to rename the model declaration files manually.

Friday, January 3, 2014

Rename a Database column using Rails migration

You need to create a separate migration to do this.

rails g migration FixColumnName

class FixColumnName < ActiveRecord::Migration
  def change
    rename_column :table_name, :old_column, :new_column
  end
end

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again.
rename_column :table_name, :old_column1, :new_column1
rename_column :table_name, :old_column2, :new_column2
...
You could use change_table to keep things a little neater.
class FixColumnNames < ActiveRecord::Migration
  def change
    change_table :table_name do |t|
      t.rename :old_column1, :new_column1
      t.rename :old_column2, :new_column2
      ...
    end
  end
end