Bryan is an entrepreneur, software developer, photographer, investor and business adviser with a strong operations background coupled with 16 years of startup, new media, early-stage financing, marketing, technology development, sales and real estate investment experience.

a

Tips: Rails DB Fun

Tips: Rails DB Fun

You’ve been working on spec’ing out your app and maybe you jumped the gun a little. So what do you do if you’ve been working and you’d like to change the name to better reflect what you’re working now. Not too difficult.

The change method is the primary way of writing migrations. It works for the majority of cases, where Active Record knows how to reverse the migration automatically. Currently, the change method supports only these migration definitions:

  • add_column
  • add_foreign_key
  • add_index
  • add_reference
  • add_timestamps
  • change_column_default (must supply a :from and :to option)
  • change_column_null
  • create_join_table
  • create_table
  • disable_extension
  • drop_join_table
  • drop_table (must supply a block)
  • enable_extension
  • remove_column (must supply a type)
  • remove_foreign_key (must supply a second table)
  • remove_index
  • remove_reference
  • remove_timestamps
  • rename_column
  • rename_index
  • rename_table

change_table is also reversible, as long as the block does not call changechange_default or remove.

CREATE A NEW MIGRATION

For my example, I’ll call it BigChange. From the console:

UPDATE YOUR MIGRATION

You can change as many column names as you want in this migration:

class Changename < ActiveRecord::Migration
def change
rename_column :table, :old_name, :new_name
rename_column :table, :old_name, :new_name
end
end

MIGRATE

That’s about it. Nice and easy. Now just make sure you change any references to this you may have in your app.

 

Rolling Back

What if you messed a migration well just roll it back.

rails db:rollback

This will rollback the latest migration, either by reverting the change method or by running the down method.

 

Redo

rails db:migrate:redo

The db:migrate:redo command is a shortcut for doing a rollback and then migrating again.

 

Steps

Do you want to rollback more than just one level back? Well just add in steps.

rails db:rollback STEP=4

This will revert the last 4 migrations.

You can even throw it into the redo from above.

rails db:migrate:redo STEP=4

 

That’s it, a few rails db tips. Now go and break your database.


Also published on Medium.

Tags:
, ,