I am looking for ways to write migrations in rails that can be executed against the database many times without failing.
For instance let say I have this migration:
For Rails 3.X, there's the column_exists?(:table_name, :column_name)
method.
For Rails 2.X, you can check the existence of columns with the following:
columns("").index {|col| col.name == ""}
...or if you're not in a migration file:
ActiveRecord::Base.connection.columns("").index {|col| col.name == ""}
If it returns nil, no such column exists. If it returns a Fixnum, then the column does exist. Naturally, you can put more selective parameters between the {...}
if you want to identify a column by more than just its name, for example:
{ |col| col.name == "foo" and col.sql_type == "tinyint(1)" and col.primary == nil }
- 热议问题