I have following two migrations:
One, Add column contextual_page_number to transcripts table:
class AddContextualPageNumberToTranscripts < ActiveRecord::Migration[5.2]
def change
add_column :transcripts, :contextual_page_number, :integer, default: 1
end
end
Second, changing the value of the previous added column contextual_page_number based on value of another column:
class ChangePageOffsetAndContextualPageNumberOfTranscripts < ActiveRecord::Migration[5.2]
def up
Firm.all.find_in_batches do |group|
group.each do |firm|
Apartment::Tenant.switch(firm.tenant) do
Transcript.where.not(page_offset: 0).each do |transcript|
transcript.update(
contextual_page_number: ((transcript.page_offset - 1) * -1),
page_offset: 1
)
end
end
end
end
end
def down
..
end
end
After running the migration, I am getting unknown attribute contextual_page_number error.
== 20211108132509 AddContextualPageNumberToTranscripts: migrating ============= -- add_column(:transcripts, :contextual_page_number, :integer, {:default=>1}) -> 0.0095s == 20211108132509 AddContextualPageNumberToTranscripts: migrated (0.0096s) ====
== 20220113095658 ChangePageOffsetAndContextualPageNumberOfTranscripts: migrating rails aborted! StandardError: An error has occurred, this and all later migrations canceled:
unknown attribute 'contextual_page_number' for Transcript.
I have even tried reset_column_information, but no luck:
Apartment::Tenant.switch(firm.tenant) do
Transcript.connection.schema_cache.clear!
Transcript.reset_column_information
..
end
Any clue would be of great help, thanks.
You need two migration files. First, try running the migration and check
schema.rbfor the tabletranscriptsand verify that the newly added columncontextual_page_numberis being added or not.Once you are sure that your new column is added, then again create a new migration like, eg:
MigrateTransriptsCloningsData, and then add the desired changes in theupblock, then executedb:migrateto update the required changes.My choice would be To add a new rake task and executing it. like
bundle exec rake migrate_transcripts_data:startinstead of keeping that logic in the db/migrate/your_new_migration_file, choice is yours.