I know I can do this in a change
migration and have it be reversible:
add_column :widgets, :color, :string
remove_column :widgets, :flavor, :string
But strangely, change_table
->remove
does not work like this. Instead of params (name, type)
, it takes a list of column names. (If you attempt to append a type parameter, it gets interpreted as a column name.)
change_table(:widgets) do |t|
t.column :color, :string
t.remove :flavor, :string # <-- nope! It tries to remove a column named "string"
end
When you try that, you get this error:
remove_columns is only reversible if given a type.
Is there another call I am be overlooking? It seems weird that change_table
could be missing such a fundamental use case, but I don't see any calls in the docs that can do it.
CodePudding user response:
While experimenting, I tried this and it works:
change_table(:widgets) do |t|
t.column :color, :string
t.remove :flavor, type: :string
#^^^^^
end
So I guess that's the answer.
CodePudding user response:
ActiveRecord::ConnectionAdapters::Table
is generally just a thin wrapper around ActiveRecord::ConnectionAdapters::SchemaStatements
- in this case remove_columns which takes a list of columns and an options hash.
type and other column options can be passed to make migration reversible.
remove_columns(:suppliers, :qualification, :experience, type: :string, null: false)
remove
really just provides the first argument - which is the table.