Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove column without downtime with ActiveRecord 3.1?

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?

like image 209
UncleGene Avatar asked Sep 20 '12 17:09

UncleGene


People also ask

How do you delete a column in Rails?

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.

How do you change the name of a column in Ruby on Rails?

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 ...


1 Answers

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)

like image 142
ScottJShea Avatar answered Oct 20 '22 21:10

ScottJShea