One of my favourite Single Page Application (SPA) tricks is allowing the user to edit something (like a comment) without having to leave the page they're on, a little bit like on Reddit.
Using the turbo_frame_tag
helper from the hotwire-rails gem, I was able to achieve this in about 4 lines of code! I also didn't have to touch any JavaScript or change my existing controller code.
The code
<!-- app/views/comments/_comment.html.erb -->
<%= turbo_frame_tag dom_id(comment) do %>
<blockquote>
<%= comment.body %>
<footer>
<%= link_to 'Edit', [:edit, comment.post, comment] %> | <%= l comment.updated_at, format: :long %>
</footer>
</blockquote>
<% end %>
<!-- app/views/comments/edit.html.erb -->
<h1>Editing Comment</h1>
<%= turbo_frame_tag dom_id(@comment) do %>
<%= render 'form', comment: @comment %>
<% end %>
<%= link_to 'Show', url_for([@comment.post, @comment]) %> |
<%= link_to 'Back', url_for([@comment.post]) %>
How does the tag work?
The turbo_frame_tag
helper method will wrap your block of code in a <turbo-frame id="comment_1">
tag (which is like a div, but magic!).
When a link within that tag is clicked, Turbo will perform an AJAX type request to the requested page looking for a <turbo-frame>
tag with a matching ID, if it finds one, it'll replace the content with the new content.
Top comments (3)
Thank you for this great video.
Just a reminder, we don't need to use
dom_id
after this commit github.com/hotwired/turbo-rails/co...😄
Great video, thanks.
Hey Mike, great post, such a simple solution that highly optimizes any crud operation in rails!