Rails 7 adds `config.action_text.attachment_tag_name`

Rails 7 adds support for setting the actiontext’s default attachment HTML tag name to a custom string.

Before

Until Rails 6, by default, actiontext’s default attachment HTML tag name was set to action-text-attachment.

An action text’s rich text field when rendered with an attachment would generate the following HTML:

  <div class="trix-content">
    <div>
      <action-text-attachment sgid="BAh7CEki..." content-type="image/png" url="http://localhost:3000/rails/active_storage/blobs/redirect/eyJfcmFpbHMiO.../saeloun%20logo.png" filename="saeloun logo.png" filesize="9613" width="600" height="600" previewable="true" presentation="gallery">
      <figure class="attachment attachment--preview attachment--png">
          <img src="http://localhost:3000/rails/active_storage/representations/redirect/eyJfcmFpbHMiO.../saeloun%20logo.png">

        <figcaption class="attachment__caption">
            <span class="attachment__name">saeloun logo.png</span>
            <span class="attachment__size">9.39 KB</span>
        </figcaption>
      </figure>
    </action-text-attachment>Description for the blog<br><br><br>
  </div>
</div>

We could change this tag name by parsing the rich_text output and then change the tag name using nokogiri.

After

Rails 7 added a cleaner and simpler way to do this with the option to set the default attachment HTML tag name using the following configuration option:

  # config/application.rb
  config.action_text.attachment_tag_name = "saeloun-rich-text-attachment"
<div class="trix-content">
  <div>Description for the blog<br>
    <saeloun-rich-text-attachment sgid="BAh7CEki..." content-type="image/png" url="http://localhost:3000/rails/active_storage/blobs/redirect/eyJfcmFpbHMiO.../saeloun%20logo.png" filename="saeloun logo.png" filesize="9613" width="600" height="600" previewable="true" presentation="gallery">
      <figure class="attachment attachment--preview attachment--png">
          <img src="http://localhost:3000/rails/active_storage/representations/redirect/eyJfcmFpbHMiO.../saeloun%20logo.png">

        <figcaption class="attachment__caption">
            <span class="attachment__name">saeloun logo.png</span>
            <span class="attachment__size">9.39 KB</span>
        </figcaption>
      </figure>
    </saeloun-rich-text-attachment><br><br><br>
  </div>
</div>

Note: If we change the attachment HTML tag name in an existing Rails project, all the previous attachment tag names will not be updated and hence not being rendered until we update the records with the new configuration in place.

If we try to render such a rich text record, it will skip rendering the attachment HTML entirely as the tag will be sanitized.

Restoring the tag name to the previous configuration will render the attachments as before.

Need help on your Ruby on Rails or React project?

Join Our Newsletter