DEV Community

Rails Designer
Rails Designer

Posted on • Edited on • Originally published at railsdesigner.com

Don't expose primary id's with Rails' dom_id

This article was originally published on Rails Designer


Black Friday Alert! πŸ€‘ Rails Designer is now available with a discount up to 50% 🀩


If you use Hotwire with Rails, you have most likely used dom_id. It's a clever, little helper to give a unique id to an element. This helps to easily target an element with Turbo Streams (to update, append or delete).

You use it like this:

dom_id(User)          # => "new_user"
dom_id(User.find(42)) # => "user_42"
Enter fullscreen mode Exit fullscreen mode

It is this last example I have issues with. As it exposes the primary id of that record. Depending on your app, you might not care, but when you run a (SaaS) business, this might be sensitive business information you don't want exposed.

So I created a little gem, called stealth_dom_id.

It's based on an a small class I added in my lib folder for years (there might be more candidates in there for gems 🀫). It works like this:

dom_id(User.find(42), attribute: :public_id) # "user_a1b2c3"
Enter fullscreen mode Exit fullscreen mode

You can also, just like with the unstealthy dom_id, pass a prefix attribute:

dom_id(User.find(42), :admin, attribute: :public_id) # "admin_user_a1b2c3"
Enter fullscreen mode Exit fullscreen mode

If you use dom_id in your Rails projects, I am sure you will love it. Check it out on GitHub.

Top comments (1)

Collapse
 
eclecticcoding profile image
Chuck

This is a fascinating idea.

Thank you for doing this