Removing columns from tables while running application with ActiveRecord causes errors, because ActiveRecord caches column names.
Workaround for other versions of ActiveRecord is to override #columns method in the model and filter out deprecated column names before migration (basically - hide these columns from AR). This worked because all column name related methods were based on #columns call
In ActiveRecord 3.1 caching of table structures is moved to ConnectionPool, and all column name related values (e.g. coluumns_hash) are cached independently (3.2 uses ModelSchema.columns that made this working again)
Is there any way (other than deep-hack of concrete adapters) to achieve safe column drop in ActiveRecord 3.1?
The change method can be used to drop a column in Rails 4 applications, but should not be used in Rails 3. I updated my answer accordingly. You can also use remove_column :table_name, :column_name, :type, :options within the change method, since if you specify the type reverting the migration is possible.
If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again: rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...
Luke Ludwig of TST Media offers a solution here. Essentially they "override the ActiveRecord::Base.columns method on the class whose column is being removed."
(solution applicable to all but 3.1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With