Rails 6.1 -> 7 gives 404 for ActionText attachments

ActionText relies on ActiveStorage, which generates encrypted urls. When you submit, ActionText saves that URL as part of the HTML code, so if something causes ActiveStorage urls to change, the urls in ActionText will no longer work.

The migration from rails 6 to 7 changed the key generator from SHA1 to SHA256, which should have impacted the urls in ActiveStorage, which in turn must have broken your images. Here’s a sample code I used to fix mine:

  # After active storage urls are changed, use this to recreate all trix attachments
  def self.refresh_trixes
    ActionText::RichText.where.not(body: nil).find_each do |trix|
      refresh_trix(trix)
    end
  end

  # After active storage urls are changed, use this to recreate a specific trix attachments
  def self.refresh_trix(trix)
    return unless trix.embeds.size.positive?

    trix.body.fragment.find_all("action-text-attachment").each do |node|
      embed = trix.embeds.find { |attachment| attachment.filename.to_s == node["filename"] && attachment.byte_size.to_s == node["filesize"] }

      node.attributes["url"].value = Rails.application.routes.url_helpers.rails_storage_redirect_url(embed.blob, host: "YOUR_DOMAIN")
      node.attributes["sgid"].value = embed.attachable_sgid
    end

    trix.update_column :body, trix.body.to_s
  end

Pleas make sure you test this before running in production. I’ve used a few times and it works well enough, but you never know… and also replace YOUR_DOMAIN with your actual domain.

5 Likes