samedi 29 janvier 2022

ActiveRecord::UnknownAttributeError when adding passive column

I'm trying to run this migration, and the goal is to not have any server downtime while adding new columns. Since these columns have no relationships to other tables, exist in the code, or are required, I assumed this would be possible. But, after running the migration I observed UnknownAttributeError's being thrown when instantiating a new instance of the model.

The error:

Controller/existing_table/some_method::ActiveRecord::UnknownAttributeError
/code/app/models/existing_table.rb:40:in `new’

The line from the error:

e = ExistingTable.new(existing_table.attributes.except("id"))

The migration:

class AddTestFieldToExistingTable < ActiveRecord::Migration
  def change
    add_column :existing_table, :test_field, :integer
  end
end

When I go to recreate the issue by opening up a console and executing lines similar as above, I don't get the error. My guess is that there is some attributes cached and we do need to have downtime while running these "passive" migrations.

I wonder if the 'existing_table' is still in memory, doesn't have the 'test_field' attribute, and when creating a new instance of ExistingTable it doesn't know how to assign the field. Since I cannot recreate it without starting a new instance, I would be guessing on an alternative solution of re-writing the ExistingTable constructor.

Is there a way to avoid restarting the rails instance or re-writing this code? Am I on the right track?

Aucun commentaire:

Enregistrer un commentaire