How to allow ID attributes in Action Text

Updated: 

Learn how to enable ID attributes in Action Text for enhanced content structuring in Rails applications. Improve your Ruby on Rails skills with this practical guide.

This lesson is from Full Stack Rails Mastery.

If you have an Action Text field in Rails, by default, any ID attributes on elements will be stripped out.

Even if you edit and save the HTML directly (instead of in Trix) and add ids to elements, they won't show up on the page when that HTML is rendered.

For example, let's say you have an element like this:
<div id="my-element">
Some content
</div>
 
When it's rendered, it will look like this:
<div>
Some content
</div>

This happens because the default sanitizer removes any disallowed attributes (which includes id). To overcome this, you need to add it to the whitelist of allowed attributes.

Create a new config file, say actiontext.rb, in the config directory with this line:
Rails::Html::WhiteListSanitizer.allowed_attributes << 'id'

Restart the Rails server and now you will see IDs rendered in your Action Text HTML.

If you still don't see them, it might be because of caching. Clear the cache and it should work.