How to write conditional migrations in rails?

前端 未结 4 603
悲&欢浪女
悲&欢浪女 2020-12-30 01:14

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:

4条回答
  •  一整个雨季
    2020-12-30 01:19

    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 }
    

    提交回复
    热议问题