Recently, we had a piece of code that looked something like this:
Does it look a little off to you? I’m sure you’ve seen (or even perpetrated) a scenario like this before, where you name something and when you revisit the code later you realise too late that you’ve made a typo.
We wanted to rename resumee to resume, but there was already data in the system. How do we ensure we don’t lose access to the existing resumee files when we rename the association?
Through googling I came across How to rename an ActiveStorage has_one_attached association? — which was almost exactly what I wanted. But I wasn’t sure where I should be putting the fix. I don’t have access to the production box, so just running the query through the rails console wasn’t an option for me.
So, here’s a step by step guide on how I used a migration to fix the typo in the has_one_attached association.
rails generate migration RenameTableNameTypoedNameToFixedName
- Modify the migration file so it looks like this
class RenameTableNameTypoedNameToFixedName < ActiveRecord::Migration[7.0]
.where(name: 'typoed_name', record_type: 'TableName')
.update_all name: 'fixed_name'
- Rename the attachment on the model
- Search your code for any uses of the typo and rename those too (don’t forget about comments, files, folders etc)
And you’re done!