Benito Serna Tips and tools for Ruby on Rails developers

How the turbo_frame_tag helper transforms an object to an html id?

February 8, 2022

If you are new with rails and hotwire, it could be useful to know that you can pass an object to the turbo_frame_tag and it will use a string representation of that object as an id.

For example if you have a Product record, you can do:

product = Product.find(1)
turbo_frame_tag(product)

And it will return:

<turbo-frame id="product_1"></turbo_frame>

And if you do

product = Product.new
turbo_frame_tag(product)

It will return:

<turbo-frame id="new_product"></turbo_frame>

This happen because internally turbo_frame_tag uses the dom_id helper.

def turbo_frame_tag(id, src: nil, target: nil, **attributes, &block)
  id = id.respond_to?(:to_key) ? dom_id(id) : id
  #...
end

You can see the code of the turbo_frame_tag helper here:

And the docs for the dom_id helper here:

Related articles

Subscribe to get future posts via email

Here I try to share knowledge and fixes to common problems and struggles for ruby on rails developers, like How to fetch the latest-N-of-each record or How to test that an specific mail was sent or a Capybara cheatsheet. You can see more examples on Most recent posts or all posts.