Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Migrations: Check Existence and Keep Going?

I was doing this kind of thing in my migrations:

add_column :statuses, :hold_reason, :string rescue puts "column already added" 

but it turns out that, while this works for SQLite, it does not work for PostgreSQL. It seems like if the add_column blows up, even if the Exception is caught, the transaction is dead and so the Migration can't do any additional work.

Is there any non-DB sepecific ways to check if a column or table already exist? Failing that, is there any way to get my rescue block to really work?

like image 758
Dan Rosenstark Avatar asked Oct 29 '09 17:10

Dan Rosenstark


2 Answers

As of Rails 3.0 and later, you can use column_exists? to check for the existance of a column.

unless column_exists? :statuses, :hold_reason   add_column :statuses, :hold_reason, :string end 

There's also a table_exists? function, which goes as far back as Rails 2.1.

like image 112
Tobias Cohen Avatar answered Oct 11 '22 01:10

Tobias Cohen


Or even shorter

add_column :statuses, :hold_reason, :string unless column_exists? :statuses, :hold_reason 
like image 23
SG 86 Avatar answered Oct 11 '22 01:10

SG 86