Renaming an Active Record has_one_attached Attachment: A Step-by-Step Guide

Photo of Michelle Tan

Michelle Tan

Software Developer at TokyoDev

Recently, we had a piece of code that looked something like this:

has_one_attached :resumee

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.

  • Run
rails generate migration RenameTableNameTypoedNameToFixedName
  • Modify the migration file so it looks like this
class RenameTableNameTypoedNameToFixedName < ActiveRecord::Migration[7.0]
  def change
      .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!

More about the author

Photo of Michelle Tan

Michelle Tan

Software Developer at TokyoDev

Michelle is an Australian software developer who moved to Japan in 2022. An active community member, she has a passion for travel, illustration, mentoring and promoting diversity and inclusion in tech.

🚀 Opportunities for English speaking developers in Japan

New job postings as they're listed, delivered to your inbox. Your email stays private, I don’t share or sell it to anyone.

Other articles you might like