<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alexis Chávez on Medium]]></title>
        <description><![CDATA[Stories by Alexis Chávez on Medium]]></description>
        <link>https://medium.com/@alexischvez?source=rss-d2ed8851cf42------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ERZrdChMyNkxsrAg</url>
            <title>Stories by Alexis Chávez on Medium</title>
            <link>https://medium.com/@alexischvez?source=rss-d2ed8851cf42------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 01:12:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexischvez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hotwire: Supercharged Rails forms with Turbo]]></title>
            <link>https://medium.com/@alexischvez/hotwire-supercharged-rails-forms-with-turbo-6de79bb9e374?source=rss-d2ed8851cf42------2</link>
            <guid isPermaLink="false">https://medium.com/p/6de79bb9e374</guid>
            <category><![CDATA[hotwire-rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[turbo]]></category>
            <category><![CDATA[stimulusjs]]></category>
            <category><![CDATA[turbo-frame]]></category>
            <dc:creator><![CDATA[Alexis Chávez]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 05:51:11 GMT</pubDate>
            <atom:updated>2023-11-01T05:51:41.938Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Rails 7 featured the new addition of Hotwire which is a bundle of frontend tools that allow us to build modern and fast web applications without writing any JavaScript(most of the times). The idea of Hotwire is to send HTML “over the wire” instead of JSON, this means that the server will deliver directly the HTML that should be rendered, reducing the overhead.</p><p>This article will work as an introduction for Turbo, which is the heart of Hotwire.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*dW4ea2M1bO-ZL-lIkI_JNA.gif" /></figure><h3>What is turbo?</h3><p>Turbo is a simplified collection of techniques that enhance the speed of page transitions and form submissions. It allows us to break down complex web pages into smaller components and stream partial page updates over WebSocket. All without writing any JavaScript at all!</p><p>These techniques are:</p><h4><strong>Turbo Drive</strong></h4><p>Turbo Drive offers the speed benefits of traditional single-page applications (SPAs) without requiring developers to build their entire application around the SPA paradigm. By intercepting link clicks and form submissions, Turbo Drive leverages a persistent-process model to render HTML responses and seamlessly update page content, providing a simplified and efficient approach to achieving high-speed user experiences.</p><h4><strong>Turbo Frames</strong></h4><p>Turbo Frames allows you to organize independent segments of a web page into frame elements, enabling scoped navigation and lazy loading. Each frame operates within its own scope, it can be appended, prepended, replaced or removed without reloading the entire page.</p><h4><strong>Turbo Streams</strong></h4><p>Turbo Streams provides the ability to update any part of a web page in response to updates received through WebSocket connections, SSE, or other transports. This enables dynamic changes to the page, such as automatically updating an inbox when a new email arrives, and enhances the interactive and responsive nature of the application.</p><h3>Building forms with Turbo</h3><p>In this post our main focus will be Turbo Frames and we will be building a To-Do list that will behave as a SPA, making all our actions happen in the index.</p><h4>Anatomy of a Turbo Frame</h4><p>We can create a Frame by wrapping content or a segment of the page in a &lt;turbo-frame&gt; element.</p><pre>&lt;turbo-frame id=&quot;list&quot;&gt;<br>  &lt;div&gt;<br>    ...<br>  &lt;/div&gt;<br>&lt;/turbo-frame&gt;</pre><p>Frames require a unique ID, which is used to match the content being replaced when requesting new pages from the server.</p><p>This custom element intercepts interactions within the frame, making it a distinct component of your webpage. By default, links and forms within the frame aim to update only the content of that specific frame, whether the server sends a completely new HTML document or just a page fragment.</p><p>We can also render a Turbo Frame with the built-in helper from Turbo Rails:</p><pre>&lt;%= turbo_frame_tag &quot;list&quot; do %&gt;<br>  &lt;div&gt;<br>    ...<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><h4>Creating a new to-do</h4><p>Our to-do list currently looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*sb58YF8YGh--egckYnQijg.png" /><figcaption>/to_dos/index</figcaption></figure><p>Right now when we click the “Add<strong>+”</strong> button we get redirected to a “new” to-do form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*Yx9gk8_DwkH3i2RRqVeSoA.png" /><figcaption>/to_dos/new</figcaption></figure><p>We actually want the form to be appended in our index view instead of being redirected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-7d3KweLU3y_ZLpnRTYPQ.png" /></figure><p>Let’s wrap our “Add +” button within a Turbo Frame and call it new_to_do_frame.</p><pre># app/views/to_dos/index.html.erb<br><br>&lt;div class=&quot;container&quot;<br>  &lt;%= turbo_frame_tag &quot;new_to_do_frame&quot; do %&gt;<br>    &lt;div class=&quot;header&quot;&gt;<br>      &lt;h3 class=&quot;text-5xl&quot;&gt;to-dos list&lt;/h3&gt;<br>      &lt;%= link_to new_to_do_path &quot;Add +&quot; %&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br>  <br>  &lt;ul role=&quot;list&quot;&gt;<br>    &lt;%= render @to_dos %&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>We should be able to see the HTML our Turbo Frame generated in the DOM now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLmLwLrcHZlzn2aAAhIQHQ.png" /></figure><p>Let’s click the “Add +” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9-29CLiUR6Re4UTZ0CHJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebQUkW3DMOZGdjFW0HJmGA.png" /></figure><p>Let’s break down what’s happening in this scenario.</p><p>Turbo is expecting a frame with the same id on the target page to replace the existing content with. However, if there is no frame with a matching id, Turbo will remove the content from the source page Turbo Frame and log an error message. In this case, our target page is app/views/to_dos/new .</p><p>Adding a matching Turbo Frame:</p><pre># app/views/to_dos/new.html.erb<br><br>&lt;%= turbo_frame_tag &quot;new_to_do_frame&quot; do %&gt;<br>  &lt;%= render &quot;form&quot;, to_do: @to_do %&gt;<br>&lt;% end %&gt;</pre><p>If we refresh our page and click the “Add +” button we will see the content of our source Turbo Frame in the index page being replaced(filled) by the content of our target Turbo Frame in the new page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b1Z7lr1VWgrJ8uhahAczw.png" /></figure><p>It looks good! And it’s all happening in real time! No page reloading.</p><p>What happens if we try to submit a new to-do?</p><p>If you click the “Create” button a new to-do will be created but it won’t show in the list until we refresh the page. We want our new to-do to be appended to our list in real time as well right?</p><p>To do this, we need to learn about Turbo Streams. But before doing that, we’ll briefly checkout the data-turbo-frame data attribute.</p><p>You might have noticed that our table’s header is being replaced by the form when we click “Add +”. This is because our source Turbo Frame is wrapping the table header and everything else within, which is then replaced by the content in our target Turbo Frame.</p><p>There will be times when you need to update the content of a frame using a link that isn’t directly nested in your target frame. To handle this situations, we can make use of data-turbo-frame data attribute.</p><p>Let’s try it out by rendering our new form in the table body instead of replacing the header like we intended with our first sketch. We’ll need to make a small refactor in order to implement our new feature:</p><pre># app/views/to_dos/index.html.erb<br><br>&lt;div class=&quot;container&quot;<br>  &lt;%= turbo_frame_tag &quot;new_to_do_frame&quot; do %&gt; # we will no longer need this<br>    &lt;div class=&quot;header&quot;&gt;<br>      &lt;h3 class=&quot;text-5xl&quot;&gt;to-dos list&lt;/h3&gt;<br>      &lt;%= link_to &quot;Add +&quot;<br>                  new_to_do_path,<br>                  data: { turbo_frame: &quot;data_attribute_frame&quot; } %&gt;<br><br>    &lt;/div&gt;<br>    &lt;%= turbo_frame_tag &quot;data_attribute_frame&quot; %&gt;<br>  &lt;% end %&gt;<br><br>  &lt;ul role=&quot;list&quot;&gt;<br>    &lt;%= render @to_dos %&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>Renaming our Turbo Frame in our new to-do view:</p><pre># app/views/to_dos/new.html.erb<br><br>&lt;%= turbo_frame_tag &quot;data_attribute_frame&quot; do %&gt;<br>  &lt;%= render &quot;form&quot;, to_do: @to_do %&gt;<br>&lt;% end %&gt;</pre><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4VN3nA6NkB3W0t7KyEHYg.png" /></figure><p>A link can target a Turbo Frame even if it’s wrapped within the frame using the data-turbo-frame data attribute. If the source and target pages have Turbo Frames with the same id as specified in the data-turbo-frame attribute, the target Turbo Frame will replace the source Turbo Frame.</p><h4>Turbo Streams</h4><p>In Rails 7, forms are submitted with the Turbo Stream format by default. You can see this in your Rails server logs when we create a new to-do:</p><pre>Started POST &quot;/to_dos&quot; for ::1 at 2023-08-03 14:50:49 -0600<br>Processing by ToDosController#create as TURBO_STREAM</pre><p>We can make use of Turbo Streams to have our create action to exclusively append the Turbo Frame containing the recently created to-do without affecting the rest of the page. Let’s update our to_dos_controller so it knows to support both HTML and Turbo Stream formats.</p><pre># app/controllers/to_dos_controller.rb<br><br>def create<br>  @to_do = ToDo.new(to_do_params)<br>  if @to_do.save<br>    respond_to do |format|<br>      format.html { redirect_to to_dos_path }<br>      format.turbo_stream<br>    end<br>  else<br>    render :new, status: 422<br>  end<br>end</pre><p>We also need to create the corresponding view for our Turbo Streams format:</p><pre># app/views/to_dos/create.turbo_stream.erb<br><br>&lt;%= turbo_stream.prepend &quot;to_dos&quot;, partial: &quot;to_dos/to_do&quot;, locals: { to_do: @to_do } %&gt;</pre><p>So what’s happening here?</p><p>We’re telling Turbo to prepend to the element with id “to_dos” the to_dos/_to_do partial and its locals.</p><p>We just need to add a Turbo Frame with id “to_dos” wrapping our list of to-dos in the to_dos/index page:</p><pre># app/views/to_dos/index.html.erb<br><br>&lt;div class=&quot;container&quot;<br>  &lt;%= turbo_frame_tag &quot;new_to_do_frame&quot; do %&gt;<br>    &lt;div class=&quot;header&quot;&gt;<br>      &lt;h3 class=&quot;text-5xl&quot;&gt;to-dos list&lt;/h3&gt;<br>      &lt;%= link_to &quot;Add +&quot;<br>                  new_to_do_path,<br>                  data: { turbo_frame: &quot;data_attribute_frame&quot; } %&gt;<br><br>    &lt;/div&gt;<br>    &lt;%= turbo_frame_tag &quot;data_attribute_frame&quot; %&gt;<br>  &lt;% end %&gt;<br><br>  &lt;ul role=&quot;list&quot;&gt;<br>    &lt;%= turbo_frame_tag &quot;to_dos&quot; do %&gt;<br>      &lt;%= render @to_dos %&gt;<br>    &lt;% end %&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>Let’s submit our form one more time and inspect the Network tab in the dev tools. This is our response body:</p><pre>&lt;turbo-stream action=&quot;prepend&quot; target=&quot;to_dos&quot;&gt;&lt;template&gt;&lt;li class=&quot;flex items-center justify-between gap-x-6 py-5&quot;&gt;<br>  &lt;div class=&quot;min-w-0&quot;&gt;<br>    &lt;div class=&quot;flex items-start gap-x-3&quot;&gt;<br>      &lt;h1 class=&quot;text-2xl font-extrabold leading-none tracking-tight text-gray-900&quot;&gt;write blogpost&lt;/h1&gt;<br>      &lt;p class=&quot;rounded-md whitespace-nowrap mt-0.5 px-1.5 py-0.5 text-xs font-medium ring-1 ring-inset text-green-700 bg-green-50 ring-green-600/20&quot;&gt;Complete&lt;/p&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;flex flex-none items-center gap-x-4&quot;&gt;<br>    &lt;form class=&quot;button_to&quot; method=&quot;post&quot; action=&quot;/to_dos/18&quot;&gt;&lt;input type=&quot;hidden&quot; name=&quot;_method&quot; value=&quot;delete&quot; autocomplete=&quot;off&quot; /&gt;&lt;button type=&quot;submit&quot;&gt;<br>      &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; fill=&quot;none&quot; viewBox=&quot;0 0 24 24&quot; stroke-width=&quot;1.5&quot; stroke=&quot;currentColor&quot; class=&quot;w-6 h-6 text-gray-600 hover:text-gray-400&quot;&gt;<br>        &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; d=&quot;M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10&quot; /&gt;<br>      &lt;/svg&gt;<br>&lt;/button&gt;&lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; value=&quot;N-X93fx1gJtROeZFUg05iS4BOenmDMDAU4XqxY72Wd5pCo13TmIbuQhxTd1_GMoMw4lz9otDhRv-x5PTyPGjyg&quot; autocomplete=&quot;off&quot; /&gt;&lt;/form&gt;<br>    &lt;div class=&quot;relative flex-none&quot;&gt;<br>      &lt;form class=&quot;button_to&quot; method=&quot;post&quot; action=&quot;/to_dos/18&quot;&gt;&lt;input type=&quot;hidden&quot; name=&quot;_method&quot; value=&quot;delete&quot; autocomplete=&quot;off&quot; /&gt;&lt;button type=&quot;submit&quot;&gt;<br>        &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; fill=&quot;none&quot; viewBox=&quot;0 0 24 24&quot; stroke-width=&quot;1.5&quot; stroke=&quot;currentColor&quot; class=&quot;w-6 h-6 text-gray-600 hover:text-red-400&quot;&gt;<br>          &lt;path stroke-linecap=&quot;round&quot; stroke-linejoin=&quot;round&quot; d=&quot;M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0&quot; /&gt;<br>        &lt;/svg&gt;<br>&lt;/button&gt;&lt;input type=&quot;hidden&quot; name=&quot;authenticity_token&quot; value=&quot;Vo0IR3SpnffMs9hhSithLAsyqVtDe1jgTy2H6Nc8yLgIYnjtxr4G1ZX7c_lnPpKp5rrjRC40HTvib_7-kTsyrA&quot; autocomplete=&quot;off&quot; /&gt;&lt;/form&gt;    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/li&gt;&lt;/template&gt;&lt;/turbo-stream&gt;</pre><p>We can see that a Turbo Stream message is a fragment of HTML consisting of &lt;turbo-stream&gt; elements. Each element has an action and a target matching our create.turbo_stream.rb view as well as a &lt;template&gt; element wrapping its included HTML.</p><p>Our to-do creation should be working as expected now.</p><p>Here’s a list of methods that Turbo Streams responds to:</p><pre>turbo_stream.remove<br><br>turbo_stream.append<br><br>turbo_stream.prepend<br><br>turbo_stream.before<br><br>turbo_stream.after<br><br>turbo_stream.update<br><br>turbo_stream.replace</pre><p>We can refactor our Turbo Stream view using the <a href="https://boringrails.com/articles/rails-dom-id-the-most-underrated-helper/">dom_id</a> helper:</p><pre>&lt;%= turbo_stream.prepend &quot;to_dos&quot;, @to_do %&gt;<br>&lt;%= turbo_stream.update ToDo.new, &quot;&quot; %&gt; # this will remove our new to-do frame after submission</pre><p>The turbo_frame_tag helper automatically passes the given object to the dom_id helper to convert our to_do object into a unique id as well:</p><pre>turbo_frame_tag &quot;to_do#{@to_do.id}&quot; # =&gt; &quot;to_do_1&quot;<br>turbo_frame_tag @to_do              # =&gt; &quot;to_do_1&quot;</pre><p>As well as our Turbo Frame tags:</p><pre># app/views/to_dos/index.html.erb<br><br>&lt;div class=&quot;container&quot;<br>  &lt;div class=&quot;header&quot;&gt;<br>    &lt;h3 class=&quot;text-5xl&quot;&gt;to-dos list&lt;/h3&gt;<br>    &lt;%= link_to &quot;Add +&quot;<br>                new_to_do_path,<br>                data: { turbo_frame: dom_id(ToDo.new) } %&gt;<br><br>  &lt;/div&gt;<br>  &lt;%= turbo_frame_tag ToDo.new %&gt;<br><br>  &lt;ul role=&quot;list&quot;&gt;<br>    &lt;%= turbo_frame_tag &quot;to_dos&quot; do %&gt;<br>      &lt;%= render @to_dos %&gt;<br>    &lt;% end %&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><pre># app/views/to_dos/new.html.erb<br><br>&lt;%= turbo_frame_tag @to_do do %&gt;<br>  &lt;%= render &quot;form&quot;, to_do: @to_do %&gt;<br>&lt;% end %&gt;</pre><h4>Editing a to-do</h4><p>To edit a to-do we want to replace the list item that contains our to-do with the edition form when clicking on the “Edit”. In order to achieve this we’ll need to wrap each item in a unique Turbo Frame and we’ll need to do it in a dynamic way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQ-JP8rqh4Vp9G4waHW_wg.png" /></figure><p>Let’s go ahead and wrap each of our to-dos in a Turbo Frame with a unique id.</p><pre># app/views/to_dos/_to_do.html.erb<br><br>&lt;%= turbo_frame_tag to_do do %&gt;<br>  &lt;div class=&quot;to_do&quot;&gt;<br>    &lt;li&gt;<br>      &lt;h1 class=&quot;text-2xl&gt;&lt;%= to_do.title %&gt;&lt;/h1&gt;<br>      &lt;div class=&quot;actions&quot;&gt;<br>        &lt;%= button_to &quot;Delete&quot;, to_do_path(to_do), method: :delete %&gt;<br>        &lt;%= link_to &quot;Edit&quot;, edit_to_do_path(to_do) %&gt;<br>      &lt;/div&gt;<br>    &lt;/li&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><p>We need another Turbo Frame of the same id around our edit form:</p><pre># app/views/to_dos/edit.html.erb<br><br>&lt;%= turbo_frame_tag @to_do do %&gt;<br>  &lt;h1 class=&quot;title&quot;&gt;Edit to-do&lt;/h1&gt;<br><br>  &lt;%= render &quot;to_dos/form&quot;, to_do: @to_do %&gt;<br>&lt;% end %&gt;</pre><p>Our edit functionality is now working as expected!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gmFGEXA2icYF-Dmddke6g.png" /></figure><h4>Deleting a to-do</h4><p>If we click on the trashcan to delete a to-do, an error will be logged in the console and a content missing message will be rendered. This is a similar issue we had earlier where turbo is expecting to find a Turbo Frame with the same id on the target page but the destroy response has no matching &lt;turbo-frame id=&quot;to-do-id&quot;&gt;causing the frame to disappear and an error to be logged.</p><p>If we refresh the page we can see the to-do was actually removed, but how can we fix Turbo logging an error and having to refresh the page every time we want to remove a to-do?</p><p>We can make use of turbo stream in a very similar way we implement our create functionality. First, let’s add Turbo Stream format support to our destroy action:</p><pre># app/controllers/to_dos_controller.rb<br><br>def destroy<br>  @to_do = ToDo.find(params[:id])<br>  @to_do.destroy<br><br>  respond_to do |format|<br>    format.html { redirect_to to_dos_path }<br>    format.turbo_stream<br>  end<br>end</pre><p>Just like with any other format, we need to create the corresponding view:</p><pre># app/views/to_dos/destroy.turbo_stream.erb<br><br>&lt;%= turbo_stream.remove @to_do %&gt;</pre><p>If we click the trashcan one more time, Turbo will now know to remove the Turbo Frame of the specified to-do id leaving the rest of the page untouched.</p><h4>Cancel button</h4><p>We now have a fully functional to-dos application but it could still use a few improvements. The only way for a user to cancel the creation or edition of a to-do is to refresh the page or submit the form. We can add a ‘cancel’ button right next to the ‘submit’ button in our to-dos form:</p><pre># app/views/to_dos/_form.html.erb<br><br>&lt;%= form_with(model: to_do, url: to_do.persisted? ? to_do_path(to_do) : to_dos_path, method: to_do.persisted? ? :patch : :post, class: &quot;mt-20&quot;) do |form| %&gt;<br>  &lt;% if form.object.errors.any? %&gt;<br>    &lt;div id=&quot;error_explanation&quot;&gt;<br>      &lt;h3 class=&quot;text-sm font-medium text-red-800&quot;&gt;&lt;%= pluralize(form.object.errors.count, &quot;error&quot;) %&gt; prohibited this item from being saved:&lt;/h3&gt;<br>      &lt;div class=&quot;mt-2 text-sm text-red-700&quot;&gt;<br>        &lt;% form.object.errors.full_messages.each do |message| %&gt;<br>          &lt;p&gt;&lt;%= message %&gt;&lt;/p&gt;<br>        &lt;% end %&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br>  &lt;%= form.text_field :title %&gt;<br>  &lt;%= link_to &quot;Cancel&quot;, to_dos_path, class: &quot;button-secondary&quot; %&gt;<br>  &lt;%= form.submit to_do.persisted? ? &quot;Edit&quot; : &quot;Create&quot;, class: &quot;button-primary&quot; %&gt;<br>&lt;% end %&gt;</pre><p>Since our cancel button is a link within a Turbo Frame, Turbo will only replace the content of this frame instead of reloading the whole page. Go ahead and test it, try editing, creating, canceling or deleting multiple to-dos at once. You’ll notice that the state of the page is preserved. This is because Turbo Frames are independent pieces of the page that we can easily manipulate without writing any JavaScript.</p><p>The result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7uYkyehel5dn0nvF9cDoA.png" /></figure><h4>Bonus: Using a modal to create a new to-do</h4><p>Remember the last section where I was bragging about not using any JavaScript? While Turbo usually takes care of most of the interactivity that traditionally would have required JavaScript, there are still cases where a dash of custom code is required. This is where Stimulus comes in.</p><p>According to the Stimulus handbook:</p><blockquote>Stimulus is a modest JavaScript framework, it works by connecting JavaScript objects to elements on the page using simple annotations. These JavaScript objects are called controllers and Stimulus continuously monitors the page waiting for HTML data-controller attributes to appear. For each attribute, Stimulus looks at the attribute’s value to find a corresponding controller class, creates a new instance of that class, and connects it to the element.</blockquote><p>Right now when we open up a new or edit form, a Turbo Frame with the form gets appended inside our to-dos list. Instead, we want to make the creation of new items happen in a modal.</p><p>First, we’ll add a ‘modal’ Turbo Frame to the application’s layout, this is a good way to ensure there is always an empty modal on every page and we can target it from anywhere in the application:</p><pre># app/views/layouts/application.html.erb<br><br>&lt;body&gt;<br>  &lt;%= yield %&gt;<br>    &lt;%= turbo_frame_tag &quot;modal&quot; %&gt;<br>  &lt;/div&gt;<br>&lt;/body&gt;</pre><p>Now update the turbo_frame_tag id in new.html.erb :</p><pre># app/views/to_dos/new.html.erb<br><br>&lt;%= turbo_frame_tag &quot;modal&quot; do %&gt;<br>  &lt;div class=&quot;modal&quot;&gt;<br>    &lt;div class=&quot;relative z-10&quot; aria-labelledby=&quot;modal-title&quot; role=&quot;dialog&quot; aria-modal=&quot;true&quot;&gt;<br>      &lt;div class=&quot;fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity&quot;&gt;&lt;/div&gt;<br>  <br>      &lt;div class=&quot;fixed inset-0 z-10 overflow-y-auto&quot;&gt;<br>        &lt;div class=&quot;flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0&quot;&gt;<br>          &lt;div class=&quot;relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6 animate-fade-in-up&quot;&gt;<br>            &lt;div class=&quot;mt-3 text-center sm:mt-5&quot;&gt;<br>              &lt;div class=&quot;mt-2&quot;&gt;<br>                &lt;h1 class=&quot;mb-4 mt-8 text-4xl font-extrabold leading-none tracking-tight text-gray-900 md:text-5xl lg:text-3xl&quot;&gt;New to-do&lt;/h1&gt;<br>                &lt;%= render &quot;to_dos/form&quot;, to_do: @to_do %&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;mt-5 sm:mt-6&quot;&gt;<br>              &lt;%= button_to &quot;Go back&quot;, &quot;#&quot;, class: &quot;inline-flex w-full justify-center rounded-md bg-gray-400 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-gray-300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600&quot; %&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><p>(Note: I’m using tailwind css to style the modal)</p><p>Next, we need to modify the link_to data attribute to target our ‘modal’ Turbo Frame:</p><pre># app/views/to_dos/index.html.erb<br><br>&lt;%= link_to &quot;Add +&quot;<br>                  new_to_do_path,<br>                  data: { turbo_frame: &quot;modal&quot; } %&gt;</pre><p>Try creating a new to_do, you should now see the form popping up in the form a modal. Our modal is almost complete now, you might notice the modal is refusing to close if we either submit the form or click the “Go back” button. We need to create a stimulus controller that handles closing our modal.</p><pre># app/javascript/controllers/modal_controller.js<br><br>import { Controller } from &quot;@hotwired/stimulus&quot;<br><br>export default class extends Controller {<br>  static targets = [&quot;modal&quot;]<br><br>  hideModal() {<br>    this.element.parentElement.removeAttribute(&quot;src&quot;)<br>    this.modalTarget.remove()<br>  }<br><br>  submitEnd(e) {<br>    if (e.detail.success) {<br>      this.hideModal()<br>    }<br>  }<br>}<br></pre><p>Finally we need to add the data-attributes to our modal so Stimulus can connect the controller to our modal.</p><pre>&lt;%= turbo_frame_tag &quot;modal&quot; do %&gt;<br>  &lt;div class=&quot;modal&quot; data-controller=&quot;modal&quot; data-modal-target=&quot;modal&quot; data-action=&quot;turbo:submit-end-&gt;modal#submitEnd&quot;&gt;<br>  ...<br>  &lt;%= button_to &quot;Go back&quot;, &quot;#&quot;, data: { action: &quot;modal#hideModal&quot; } %&gt;<br>&lt;% end %&gt;</pre><p>Don’t forget to add the data-action to the “Go back” button to close the modal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeexWT5F6QM4L-vc9IzE2A.png" /></figure><p>Ta-da 🎉. We now have a fully functional modal that works with Turbo.</p><h4>Extra bonus: Show form errors inside the modal</h4><p>We can do one more improvement to our modal, show errors.</p><p>The first thing we need to do is to create a shared error_messages layout which will serve as a reusable template for our form errors:</p><pre># app/views/shared/_error_messages.html.erb<br><br>&lt;div class=&quot;rounded-md bg-red-50 p-4&quot; id=&quot;errors&quot;&gt;<br>  &lt;div class=&quot;flex&quot;&gt;<br>    &lt;div class=&quot;flex-shrink-0&quot;&gt;<br>      &lt;svg class=&quot;h-5 w-5 text-red-400&quot; viewBox=&quot;0 0 20 20&quot; fill=&quot;currentColor&quot; aria-hidden=&quot;true&quot;&gt;<br>        &lt;path fill-rule=&quot;evenodd&quot; d=&quot;M10 18a8 8 0 100-16 8 8 0 000 16zM8.28 7.22a.75.75 0 00-1.06 1.06L8.94 10l-1.72 1.72a.75.75 0 101.06 1.06L10 11.06l1.72 1.72a.75.75 0 101.06-1.06L11.06 10l1.72-1.72a.75.75 0 00-1.06-1.06L10 8.94 8.28 7.22z&quot; clip-rule=&quot;evenodd&quot; /&gt;<br>      &lt;/svg&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;ml-3&quot;&gt;<br>      &lt;h3 class=&quot;text-sm font-medium text-red-800&quot;&gt;Oops&lt;/h3&gt;<br>      &lt;div class=&quot;mt-2 text-sm text-red-700&quot;&gt;<br>        &lt;p&gt;&lt;%= errors %&gt;&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Next step is to add a turbo_frame_tag right at the top of our modal:</p><pre>&lt;%= turbo_frame_tag &quot;modal&quot; do %&gt;<br>  &lt;div class=&quot;modal&quot; data-controller=&quot;modal&quot; data-modal-target=&quot;modal&quot; data-action=&quot;turbo:submit-end-&gt;modal#submitEnd&quot;&gt;<br>    &lt;div class=&quot;relative z-10&quot; aria-labelledby=&quot;modal-title&quot; role=&quot;dialog&quot; aria-modal=&quot;true&quot;&gt;<br>      &lt;div class=&quot;fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity&quot;&gt;&lt;/div&gt;<br>  <br>      &lt;div class=&quot;fixed inset-0 z-10 overflow-y-auto&quot;&gt;<br>        &lt;div class=&quot;flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0&quot;&gt;<br>          &lt;div class=&quot;relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-sm sm:p-6 animate-fade-in-up&quot;&gt;<br>          # right here <br>          &lt;%= turbo_frame_tag &quot;errors&quot; %&gt;<br>           ...<br>&lt;% end %&gt;</pre><p>The final step is adjusting the create action in our to-dos controller to respond to the Turbo Stream format when a to-do is not successfully saved:</p><pre>def create<br>    @to_do = ToDo.new(to_do_params)<br>    if @to_do.save<br>      respond_to do |format|<br>        format.html { redirect_to to_dos_path }<br>        format.turbo_stream<br>      end<br>    else<br>      render turbo_stream: turbo_stream.update(&quot;errors&quot;, partial: &quot;shared/error_messages&quot;, locals: { errors: @to_do.errors.full_messages }), status: :unprocessable_entity<br>    end<br>  end</pre><p>With the above code we are letting Turbo know to update the ‘errors’ turbo_frame_tag with the content inside our _error_messages partial whenever a to-do fails to save. The final result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwiutAqkE_-AyWbZqKeQyQ.png" /></figure><p>We’re done! Our application should now be complete and work as expected. Let’s have a recap:</p><ul><li>Turbo Frames serve well for simple functionalities, where individual page sections have their dedicated navigation and actions.</li><li>Turbo Streams, on the other hand, is better in scenarios demanding more advanced capabilities that Turbo Frames can’t cover, particularly when various segments of a page need to dynamically adapt to external data changes, like with AJAX calls.</li><li>Stimulus can be used in situations where you need to perform tasks that specifically require JavaScript . For example, showing or hiding elements dynamically.</li></ul><p>If you want to take a look at the repo of the app I used to demo, click <a href="https://github.com/AlexisChavez97/to-dos/">this link</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6de79bb9e374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real time Rails (Introduction to ActionCable)]]></title>
            <link>https://medium.com/@alexischvez/real-time-rails-introduction-to-actioncable-b18f9adb6430?source=rss-d2ed8851cf42------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18f9adb6430</guid>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Alexis Chávez]]></dc:creator>
            <pubDate>Wed, 27 Feb 2019 20:20:53 GMT</pubDate>
            <atom:updated>2020-03-05T02:40:58.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real time Rails (Introduction to ActionCable) Rails 5</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gbupJ_Z2hqozRedr0ycUA.png" /></figure><p>Rails 5 introduced ActionCable which is a built-in module that integrates WebSockets with the rest of your application and sets up both the server and the client side in a rails-magic-friendly way which means that you don’t actually need to know much about WebSockets or how they work in the background.</p><h3>The WebSocket Protocol</h3><p>Since this post is Rails ActionCable focused I’ll just take a minute of your time to briefly explain the WebSocket Protocol and how they work.</p><p>WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. So instead of having a one way communication between server and client, the client requests and initiates a full-duplex communication with the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN_2ztj-5l23QlMZvQGumA.png" /></figure><p>An Upgrade header is added when the client first makes the request and informs the server that the client wishes to establish a WebSocket connection.</p><p>The client request looks something like this:</p><pre>GET /chatroom<br>Origin: http://michelada.io<br>Connection: Upgrade<br>Host: websocket.server.com<br>Upgrade: websocket</pre><p>Then if the server supports a WebSocket connection the response will look something like this:</p><pre>HTTP/1.1 101 WebSocket Protocol Handshake<br>Date: Wed, 16 Oct 2013 10:07:34 GMT<br>Connection: Upgrade<br>Upgrade: WebSocket</pre><p>The handshake is now complete and the initial HTTP connection will be replaced with a WebSocket connection and both server and client can start sending data.</p><p>Want to know more about WebSockets? This post should help you.</p><p><a href="https://blog.teamtreehouse.com/an-introduction-to-websockets">An Introduction to WebSockets | Treehouse Blog</a></p><h3>Back to Rails now</h3><p>To start setting up ActionCable we’ll need to create a route for our WebSocket communication to take place.</p><pre># routes.rb</pre><pre>mount ActionCable.server, at: &#39;/cable&#39;</pre><p>Now communication via that route will be available. Our next step will be to create a channel. You can think of channels as controllers; they are classes that encapsulate a logical unit of work, they accept connections and trigger an action. Alright so let’s go ahead and create one:</p><p>rails generate channel chatroom</p><p>The command above will create the following files:</p><pre>create  app/channels/chatroom_channel.rb<br>identical  app/assets/javascripts/cable.js<br>create  app/assets/javascripts/channels/chatroom.coffee</pre><p>Users subscribe to channels, acting as subscribers. Their connection is called a subscription. We will route our messages to our chatroom_channel and the subscribed method will be “streaming” them.</p><p>Now in our chatroom coffeescript file we have three functions which are:</p><ul><li>connected Called when the subscription is ready for use in the server.</li><li>disconnected Called when the subscription has been terminated by the server.</li><li>received Called when there’s incoming data on the websocket for this channel.</li></ul><p>Our next step will be to subscribe to our channel, we can do this by uncommenting the subscribed method:</p><pre>#chatroom_channel.rb</pre><pre>def subscribed<br>  stream_from &quot;chatroom_channel&quot;<br>end</pre><p>Now if we start our rails server you should notice your connection being upgraded to websocket.</p><pre>Started GET &quot;/cable&quot; for 127.0.0.1 at 2019-02-26 12:38:28 -0600<br>Started GET &quot;/cable/&quot; [WebSocket] for 127.0.0.1 at 2019-02-26 12:38:28 -0600<br>Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)<br>ChatroomChannel is transmitting the subscription confirmation<br>ChatroomChannel is streaming from chatroom_channel</pre><p>Having our connection up and running we can start streaming our data. In my app I have a MessagesController and a ChatroomController , the first one is in charge of creating messages while chatroom is where our messages will be displayed.</p><pre><em># messages_controller.rb</em><br></pre><pre><em>def</em> create</pre><pre>  message = current_user.messages.build(message_params)</pre><pre><em>  if</em> message.save<br>    redirect_to root_path<br>  <em>end<br>end</em></pre><p>Now if we want to broadcast messages we would need to add the ActionCable method and add our channel’s name inside the quotes.</p><pre><em># messages_controller.rb</em><br></pre><pre><em>def</em> create</pre><pre>  message = current_user.messages.build(message_params)</pre><pre><em>  if</em> message.save</pre><pre>    ActionCable.server.broadcast &quot;chatroom_channel&quot;</pre><pre><em>  end<br>end</em></pre><p>This method takes a hash and whatever we send inside will be received by received: (data) in our chatroom.coffee file. For example:</p><pre># messages_controller.rb</pre><pre><em>def</em> create</pre><pre>  message = current_user.messages.build(message_params)</pre><pre><em>  if</em> message.save<br>    ActionCable.server.broadcast &quot;chatroom_channel&quot;,<br>                                 foo: message.body</pre><pre><em>  end<br>end</em></pre><p>Our key is foo and the value is our message’s body, this means we now have access to the message’s body in our chatroom.coffee file through data.</p><pre># chatroom.coffee</pre><pre>received: (data) -&gt;<br>  alert data.foo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVCgo0KYG9z3sqAByJYINg.png" /></figure><p>Great, it’s working! Wait, the messages aren’t displayed yet, how can we achieve this? Well we can use the append method but we would first need to give an id to our messages.</p><pre># chatroom/index.html.erb</pre><pre>&lt;div <em>class</em>=&quot;ui two column grid&quot;&gt;<br>  &lt;div <em>class</em>=&quot;twelve wide column&quot;&gt;<br>    &lt;div <em>class</em>=&quot;ui fluid raised card chatbox&quot;&gt;<br>      &lt;div <em>class</em>=&quot;content&quot;&gt;<br>        &lt;div <em>class</em>=&quot;ui feed&quot; <em>id</em>=&quot;message-container&quot;&gt;  &lt;-- &#39;add id&#39;<br>          &lt;%= render @messages %&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;div <em>class</em>=&quot;extra content&quot;&gt;<br>        &lt;%= form_for(@message, html: { class: &quot;ui reply form&quot;, role:  &quot;form&quot; }, url: message_path) <em>do</em> |f| %&gt;<br>      &lt;div <em>class</em>=&quot;field&quot;&gt;</pre><pre>        &lt;div <em>class</em>=&quot;ui fluid icon input&quot;&gt;<br>          &lt;%= f.text_field :body, placeholder: &quot;Enter message&quot;, autofocus: true %&gt;</pre><pre>          &lt;%= f.button &#39;&lt;i class=&quot;inverted orange edit icon chat&quot;&gt;&lt;/i&gt;&#39;.html_safe  %&gt;</pre><pre>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;% <em>end</em> %&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br></pre><pre># messages/_message.html.erb</pre><pre>&lt;div <em>class</em>=&quot;event&quot;&gt;<br>  &lt;div <em>class</em>=&quot;content&quot;&gt;<br>    &lt;div <em>class</em>=&quot;summary&quot;&gt;<br>      &lt;em <em>class</em>=&quot;username&quot;&gt;&lt;%= message.user.username %&gt;: &lt;/em&gt;&lt;%= message.body %&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now that we’ve added an id we can append new messages to it.</p><pre># chatroom.coffee</pre><pre>$(&#39;#message-container&#39;).append data.my_message</pre><p>We have 2 issues right now. First, our appended messages aren’t using the style in our message partial until we reload the page. Second, messages are being submitted through a POST request, what we actually want is to submit them remotely using AJAX . This will make our message submission look seamless, adding remote: true to our form should take care of this.</p><pre>&lt;div <em>class</em>=&quot;extra content&quot;&gt;<br>  &lt;%= form_for(@message, html: { class: &quot;ui reply form&quot;, role:  &quot;form&quot; }, url: message_path, remote: true) <em>do</em> |f| %&gt;</pre><p>Next step will be fixing our message style, you should’ve noticed by now we are using a message partial and instead of rendering from the view we will need to render it in our controller.</p><pre># messages_controller.rb</pre><pre><em>def</em> create</pre><pre>  message = current_user.messages.build(message_params)</pre><pre><em>  if</em> message.save<br>    ActionCable.server.broadcast &quot;chatroom_channel&quot;,<br>                                 my_message: message_render(message)</pre><pre><em>  end</em></pre><pre>private</pre><pre>def message_params<br>  params.require(:message).permit(:body)<br>end</pre><pre>def message_render(message)<br>  render(partial: &#39;message&#39;, locals: { message: message })<br>end</pre><p>We’re basically telling our controller to render the partial named ‘message’ and sending our message object through the locals hash since the partial requires a message object.</p><p>Our functionality is pretty much complete now, you might notice some details like the input not clearing after sending a message or the page not scrolling down to the most recent message but you should be able to take care of that on your own with some javascript. This would be the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxoHnzxIOR-R_-OK7o_YdQ.gif" /></figure><p>And that’s it, you now have a fully functional chat app!</p><h4>Further reading</h4><p>If you wish to learn more about ActionCable I would recommend reading the official documentation:</p><p><a href="https://guides.rubyonrails.org/action_cable_overview.html">Action Cable Overview - Ruby on Rails Guides</a></p><p>Or:</p><p><a href="https://hackernoon.com/the-practical-guide-to-using-actioncable-30d570d8988c">The Practical Guide to Using ActionCable</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18f9adb6430" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>