Jonathan Bennett

Don't use bare dom_id

dom_id is an awesome tool for letting you easily and consistently identify elements on the page, especially if they are a model:

<%= render @post %>

<!-- posts/_post.html.erb -->
<%= tag.div id: dom_id(post) do %>
  <!-- -->
<% end %>

The problem is that you might want to present the same object in different ways. You might have a post show up in the main feed, a sidebar as a related post, and on an admin page as a row in a table. If these all use the same post_123 id, you won’t be able to target them specifically when sending updates via Turbo for example.

To solve this problem, always add an extra prefix using the 2nd parameter:

<%= dom_id(@post, :card) %> => card_post_123
<%= dom_id(@post, :row) %> => row_post_123
<%= dom_id(@post, :form) %> => form_post_123