<?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[Patrik on Rails - Medium]]></title>
        <description><![CDATA[Learn how to use Ruby on Rails effectively. - Medium]]></description>
        <link>https://medium.com/patrik-on-rails?source=rss----4e5d1b29b51c---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Patrik on Rails - Medium</title>
            <link>https://medium.com/patrik-on-rails?source=rss----4e5d1b29b51c---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:41:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/patrik-on-rails" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A definitive guide to Rails’ unobtrusive JavaScript adapter]]></title>
            <link>https://medium.com/patrik-on-rails/a-definitive-guide-to-railss-unobtrusive-javascript-adapter-ef13bd047fff?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/ef13bd047fff</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[rails-ujs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Sat, 10 Feb 2018 20:35:25 GMT</pubDate>
            <atom:updated>2020-12-27T20:50:17.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEZqCX3EprIvNuRb_ya4ew.jpeg" /><figcaption>Image from <a href="https://pixabay.com/en/man-board-drawing-muscles-strong-2037255/">pixabay.com</a>.</figcaption></figure><p>This article is about <a href="https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts">rails-ujs</a>, a JavaScript library bundled with Rails. It eliminates double-click issues, provides easy to use confirmation boxes, allow non-GET requests from HTML links and last but not least it provides seamless Ajax integration with Rails.</p><h3>Double-click issues</h3><p>People tend to double-click on links and buttons. If a user double-clicks on a submit button, then the related form gets submitted twice. Have you ever seen duplicate comments on the web? They were probably caused by unhandled double-clicks.</p><p>Fortunately, rails-ujs got us covered. We don’t have to deal with double-clicks on the server-side. It is easier to disable links and form buttons after the first click. We can achieve this with the data-disable HTML attribute:</p><pre>&lt;input type=&quot;submit&quot; value=&quot;Create User&quot; <strong>data-disable=&quot;true&quot;</strong>&gt;</pre><p>It is even simpler with view helpers:</p><pre>&lt;%= submit_tag &quot;Create User&quot;, <strong>data: { disable: true }</strong> %&gt;</pre><p>This disables the button after the first click and ignores all other clicks. You can see it in the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*nultyXi2wRD4g75-oV1sjQ.gif" /><figcaption>I’ve added a two second delay to the create action.</figcaption></figure><p>We can even change the button text after the first click with data-disable-with:</p><pre>&lt;%= submit_tag &quot;Create User&quot;, <strong>data: { disable_with: &quot;Creating user...&quot; }</strong> %&gt;</pre><blockquote>data: { disable_with: &quot;Creating user...&quot; } gets translated into data-disable-with=&quot;Creating user...&quot; in the generated HTML code.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*qToDvf8rsJvEqv9ZHpnMAA.gif" /></figure><p>Double-click protection looks like a simple thing to implement, but it is not. You have to make sure that all elements are re-enabled after XHR calls (even failed ones), or that they are not disabled at all when a user opens a link in a new tab with <em>Ctrl + click</em>.</p><p>Or, you can just use data-disable or data-disable-with and do not worry about double-clicks anymore.</p><h3>Confirmation boxes</h3><p>If you have a link, button or a form with a potentially destructive action, you might want to ask your users for a confirmation before you process a request created by such element.</p><p>This is again, really easy:</p><pre>&lt;input type=&quot;submit&quot; value=&quot;Delete User&quot; <strong>data-confirm=&quot;Are you sure?&quot;</strong>&gt;</pre><p>Or with a view helper:</p><pre>&lt;%= submit_tag &quot;Delete User&quot;, <strong>data: { confirm: &quot;Are you sure&quot; }</strong> %&gt;</pre><p>This shows a standard JavaScript confirmation box after the click:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*qafjl7kD4UvA_k_0A1kU9A.gif" /></figure><h3>Make non-GET requests from links</h3><p>Let’s say you want to delete a user. You need to send a DELETE request in order to do that, but HTML links can send only GET requests.</p><p>Don’t worry, rails-ujs got you covered. You can send any type of request with data-method:</p><pre>&lt;a href=&quot;/users/1&quot; <strong>data-method=&quot;delete&quot;</strong>&gt;Delete user&lt;/a&gt;</pre><p>Or with a helper:</p><pre>&lt;%= link_to &quot;Delete user&quot;, user_path(user), <strong>data: { method: &quot;delete&quot; }</strong> %&gt;</pre><p>Also, this plays nicely with data-confirm:</p><pre>&lt;%= link_to &quot;Delete user&quot;, user_path(user), <strong>data: { method: &quot;delete&quot;, confirm: &quot;Are you sure?&quot; }</strong> %&gt;</pre><p>You can set HTTP method for links and other elements which can create XHR requests (see later).</p><p>Anyway, I said that links can create only GET requests, so how does data-method work?</p><p>You can see it <a href="https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/features/method.coffee">here</a>. But in short:</p><ol><li>rails-ujs binds to the click event on links with data-method.</li><li>When a link is clicked, then the default action is stopped and rails-ujs creates a form with action set to href from the link, set the requested method on the form and then submits it. It also takes care of CSRF tokens so you don’t need to.</li></ol><h3>Ajax (XHR) calls</h3><p>If you want to submit your action via an XHR request instead of a standard request, then you need to add data-remote=&quot;true&quot; to your element. This can be done for a link, a form or, also for input elements (see the Advanced usage section).</p><p>Example:</p><pre>&lt;a href=&quot;/users/1&quot; data-method=&quot;delete&quot; <strong>data-remote=&quot;true&quot;</strong>&gt;Delete user&lt;/a&gt;</pre><p>Or with a view helper:</p><pre>&lt;%= link_to &quot;Delete user&quot;, user_path(user), data: { method: &quot;delete&quot;, <strong>remote: true</strong> } %&gt;</pre><p>This creates an Ajax link for deleting a user. If you use Turbolinks, then you don’t have to do anything special in your controller and it will just work:</p><pre># app/controllers/users_controller.rb</pre><pre>class UserController &lt; ApplicationController<br>  def destroy<br>    User.find(params[:id]).destroy<br>    <strong>redirect_to users_path</strong><br>  end<br>end</pre><p>When you use redirect_to then <a href="https://github.com/turbolinks/turbolinks-rails">turbolinks-rails</a> generates the following response:</p><pre>Turbolinks.clearCache()<br>Turbolinks.visit(&quot;http://web.dev/users&quot;,{&quot;action&quot;:&quot;replace&quot;})</pre><p>This gets evaluated by the browser and Turbolinks redirects the user to the user index. No full page refresh is needed, everything is done via Ajax and you only needed to set two data attributes on the delete link.</p><blockquote>Do you want to learn more about Ajax on Rails? Then check out my <a href="https://m.patrikonrails.com/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38">previous articles</a> <a href="https://m.patrikonrails.com/how-to-make-ajax-calls-the-rails-way-20174715d176">about it</a>. If you want to know even more, then check out my course <a href="http://www.ajaxonrails.com/">Ajax on Rails</a>.</blockquote><h3>Integration with view helpers</h3><h4>XHR forms with form_with</h4><p>form_with adds data-remote=&quot;true&quot; by default to all forms. This can be disabled per form with local: true option, or globally in the app configuration with:</p><pre># config/initializers/action_view.rb</pre><pre>Rails.application.config.action_view.form_with_generates_remote_forms = false</pre><blockquote>Learn more about form_with in <a href="https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a">Rails 5.1’s form_with vs. form_tag vs. form_for</a>.</blockquote><h4>Automatic double-click protection for forms</h4><p>Form submit buttons created with submit_tag or submit helpers automatically add data-disable-with attribute to the generated HTML.</p><pre>&lt;%= submit_tag &quot;Submit&quot; %&gt;</pre><p>Generates:</p><pre>&lt;input type=&quot;submit&quot; name=&quot;commit&quot; value=&quot;Submit&quot; <strong>data-disable-with=&quot;Submit&quot;</strong>&gt;</pre><p>This can be disabled with:</p><pre># config/initializers/action_view.rb</pre><pre>Rails.application.config.action_view.automatically_disable_submit_tag = false</pre><p>However, I don’t see a good reason to change Rails defaults and disable automatically generated data attributes for rails-ujs.</p><h3>Advanced usage</h3><p>We already saw some basic examples, but there is even more what you can do with rails-ujs.</p><h4>Binding to the change event on form elements</h4><p>You can combine data-remote and data-url on any input, select or textarea element. This will bind to the change event on a given element. When the value of the element is changed an XHR request will be send to the URL specified in the data-url attribute.</p><p>It can be hard to come up with a good use case for this, but I got one. A to-do checkbox:</p><pre>&lt;%= check_box_tag dom_id(todo, :checkbox), nil, todo.completed?, <strong>data: { url: todo_toggles_path(todo), remote: :true, method: :post }</strong> %&gt;</pre><p>This generates a check box which will send an XHR POST request to the server when it’s value get changed.</p><h4>Set Accept header for XHR requests</h4><p>data-type changes the HTTP Accept header for XHR requests. By default it is set to:</p><pre>text/javascript, application/javascript, application/ecmascript, application/x-ecmascript</pre><p>This is great for Server-generated JavaScript Responses because it tells the server that you expect a JavaScript response.</p><p>But if you want to receive a JSON response then adddata-type=&quot;json&quot; to your element and your are done. This will set the Accept header to:</p><pre>application/json, text/javascript</pre><h4>Add additional params to XHR requests</h4><p>You can add additional params to XHR requests with data-params. However I am having a hard time creating an useful example for this feature because usually you can pass params via URL, so it doesn’t make much sense adding them to the data-params attribute.</p><p>Anyway, you can add additional params to XHR requests like this:</p><pre>&lt;%= link_to &quot;Add to cart&quot;, cart_path, data: { method: :post, remote: true, <strong>params: { product_id: product.id }.to_param</strong> } %&gt;</pre><p>This link will create an XHR POST request with product_id value in POST data.</p><h3>Subscribing to Ajax events</h3><p>When rails-ujs issues an XHR request, then it fires a bunch of different events. You can subscribe to them and stop or modify the XHR request.</p><ul><li>ajax:before — is fired before any XHR request processing. Stopping the event aborts the request.</li><li>ajax:beforeSend — is fired before the request is send. Callbacks subscribed to this event receive xhr and options objects which can be modified before the request is send. Stopping the event aborts the request.</li><li>ajax:send — is fired directly before the XHR is send if it wasn’t stopped in ajax:beforeSend. Callbacks receive the xhr object. This event is used internally by rails-ujs to disable clicked remote elements.</li><li>ajax:stopped — is fired when ajax:before or ajax:beforeSend are stopped. It is also used internally to enable disabled elements.</li><li>ajax:success — is fired after XHR request completion if the HTTP response was success.</li><li>ajax:error — is fired if the server returned an error.</li><li>ajax:complete — is fire when the request has been completed.</li></ul><h3>Conclusion</h3><p>That’s it! rails-ujs is a simple but powerful tool which integrates nicely with Rails. I hope that I did not forget anything. If I did, then please let me know and I’ll be happy to add it here.</p><p><em>If you liked this article, then please consider </em><a href="https://prodigious-writer-332.ck.page/51ce0c15e3"><em>subscribing to my personal newsletter</em></a><em> to receive more content from me. Every new subscriber makes me really happy. Thank you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef13bd047fff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/a-definitive-guide-to-railss-unobtrusive-javascript-adapter-ef13bd047fff">A definitive guide to Rails’ unobtrusive JavaScript adapter</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shell aliases (not only) for Rails developers]]></title>
            <link>https://medium.com/patrik-on-rails/shell-aliases-not-only-for-rails-developers-88ca85e5fba1?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/88ca85e5fba1</guid>
            <category><![CDATA[screencast]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[shell-alias]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Sat, 18 Nov 2017 15:32:39 GMT</pubDate>
            <atom:updated>2020-12-27T20:49:08.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5A6NImi-RWtU9efI61L5A.png" /></figure><p>In this post I am going to show you how to be more effective with command line interface thanks to the shell aliases.</p><p>A shell alias is a shortcut for a longer command. There are two types of aliases I use.</p><p>One is for commands which I use a lot. Why to type vim when I can type just v? Why to type bundle when I can type just b? Or vagrant up instead of vu?</p><p>The other is for commands which are hard to type and hard to remember. Instead of this:</p><pre>git branch --merged | grep -v &quot;\*&quot; | grep -v &quot;master&quot; | xargs git branch -d</pre><p>I use delete_merged_branches. I could probably use something shorter, but delete_merged_branches is so entrenched in my muscle memory, that I will probably keep it forever. Also, I use auto completion with it so I never type the whole name.</p><p>Check the following screencast for few more examples:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIdcHxuR8kas&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIdcHxuR8kas&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e3121ce7b1fea95b4af1c48af265f69/href">https://medium.com/media/9e3121ce7b1fea95b4af1c48af265f69/href</a></iframe><p>You can see all of my <a href="https://github.com/mrhead/dotfiles/blob/master/aliases">aliases</a> in my <a href="https://github.com/mrhead/dotfiles">dotfiles</a> repository. But don’t copy them.</p><p>If you just copy someone’s else aliases, then you can end up with a lot of aliases which you don’t use. The same thing happened to me when I created my dotfiles from <a href="https://github.com/thoughtbot/dotfiles">thoughbot dotfiles</a>. I cleaned up a lot of them since then, but there is still some bloat.</p><p>Try to identify commands which you type often, complex commands which you use regularly and define an alias for each of them so you don’t need to type or remember them anymore. This can save you a lot of time from a long-term point of view.</p><p>I hope that this post inspired you to create your own shell aliases. If yes, then feel free to share them in the comments.</p><p><em>Do you want to learn more about CLI hacks? Then </em><a href="https://prodigious-writer-332.ck.page/51ce0c15e3"><em>subscribe to my newsletter and shoot me an email</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88ca85e5fba1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/shell-aliases-not-only-for-rails-developers-88ca85e5fba1">Shell aliases (not only) for Rails developers</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make Ajax calls — The Rails way]]></title>
            <link>https://medium.com/patrik-on-rails/how-to-make-ajax-calls-the-rails-way-20174715d176?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/20174715d176</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Mon, 28 Aug 2017 18:39:42 GMT</pubDate>
            <atom:updated>2020-12-27T20:48:43.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rjh7N-WQLHzTqNdL8nPwRw.png" /></figure><p>I’ve recently read an article called <a href="https://learnetto.com/blog/how-to-make-ajax-calls-in-rails-5-1">How to make AJAX calls in Rails 5.1</a> and I have to say that I was disappointed. The article was technically correct. It mentioned three different ways to make Ajax calls, but it did not mention the “Rails way”.</p><h4>Ajax calls — The Rails way</h4><p>So what is the “Rails way” for making Ajax calls? You don’t write any JavaScript and you let Rails make Ajax calls for you!</p><p>Rails ships with an awesome unobtrusive JavaScript adapter called <a href="https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts">rails-ujs</a>. It is included in all new Rails applications. It provides us different features and one of them is seamless Ajax support.</p><p>Let’s see it in the following code samples.</p><p><strong>Link with Ajax GET request</strong></p><pre>&lt;%= link_to &quot;New user&quot;, new_user_path, <strong>remote: true</strong> %&gt;</pre><p><strong>Link with Ajax DELETE request</strong></p><pre>&lt;%= link_to &quot;Delete user&quot;, user_path(@user), <strong>remote: true, method: :delete</strong> %&gt;</pre><p><strong>Form submitted via Ajax</strong></p><pre>&lt;%= form_for @user, <strong>remote: true</strong> do |form| %&gt;<br>...<br>&lt;% end %&gt;</pre><p><strong>Even better form submitted via Ajax</strong></p><pre>&lt;%= <strong>form_with</strong> model: @user do |form| %&gt;<br>...<br>&lt;% end %&gt;</pre><p><strong>Checkbox which sends an Ajax request after it’s value changes</strong></p><pre>&lt;%= check_box_tag dom_id(todo, :checkbox), &quot;&quot;, <strong>data: { url: toggle_todo_path(todo), remote: true }</strong> %&gt;</pre><p><strong>Ajax link without Rails helpers</strong></p><pre>&lt;a href=&quot;/users/new&quot; <strong>data-remote=&quot;true&quot;</strong>&gt;Add user&lt;/a&gt;</pre><p>As you can see, it is usually enough to add remote: true to view helpers and rails-ujs will submit generated links, forms and other elements via Ajax. It will handle everything. Even the CSRF tokens.</p><p>Also, as you might or might not notice, you don’t even have to use remote: true if you use form_with, because all forms created by form_with are submitted via Ajax by default.</p><blockquote>Learn more about form_with in <a href="https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a">Rails 5.1’s form_with vs. form_tag vs. form_for</a>.</blockquote><h4>Processing request made by rails-ujs</h4><p>Now you know how to create Ajax requests without any JavaScript. But how do you process them on the server?</p><p>Actually, you process them in the same way as standard HTML requests. The only difference is that you will respond with JavaScript instead of HTML.</p><pre># app/views/new.js.erb</pre><pre>$(&quot;[data-placeholder~=user_form]&quot;).html(&quot;&lt;%= j render &quot;form&quot;, subscription: @user %&gt;&quot;);</pre><p>This template will generate a JavaScript code which finds the placeholder element and replaces it’s content with the provided HTML. This technique is called SJR (Server-generated JavaScript Responses) and you can learn more about it in my <a href="https://m.patrikonrails.com/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38">previous post</a>.</p><h4>Conclusion</h4><p>As you can see it is easier to use tools which Rails provides us. Making Ajax calls is no exception. Of course that there are use cases for manual Ajax requests, especially if you use client side rendering, but in my experience they are rare and using SJR is pretty much enough.</p><p><em>Do you want to know more? Then check out my </em><a href="http://www.ajaxonrails.com/"><em>course about Ajax on Rails</em></a><em> or </em><a href="https://prodigious-writer-332.ck.page/51ce0c15e3"><em>subscribe to my newsletter and shoot me an email</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20174715d176" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/how-to-make-ajax-calls-the-rails-way-20174715d176">How to make Ajax calls — The Rails way</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I test Rails applications]]></title>
            <link>https://medium.com/patrik-on-rails/how-i-test-my-rails-applications-cf150e347a6b?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/cf150e347a6b</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Sat, 01 Jul 2017 20:50:04 GMT</pubDate>
            <atom:updated>2020-12-27T20:48:08.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*89NN2ncgkrmIAmEue_S6yA.jpeg" /><figcaption>Is everything checked? (<a href="https://pixabay.com/en/insurance-damage-repair-checklist-539659/">pixabay.com</a>)</figcaption></figure><p>When I was a Rails beginner I was amazed by Rails and Test Driven Development. But I often struggled with testing because I did not know what to test and how to test it. As a result I wrote too much tests and I tested wrong things.</p><p>In this article I am going to describe where I ended up after 4 years with Rails and what works for me the best.</p><h4>Controller tests</h4><p>These bring me the most value. Controllers are usual entry points to Rails applications and I want to be sure that each of them is working as expected.</p><p>Don’t be fooled by the name “Controller Tests”. They don’t test only controllers anymore.</p><p>What is nice about controller tests is that they became integration tests over time. I mean literally. This is true since Rails 5. When you generate a new controller, then its test file might look like this:</p><pre># test/controllers/users_controller_test.rb</pre><pre>require &#39;test_helper&#39;</pre><pre>class UsersControllerTest &lt; <strong>ActionDispatch::IntegrationTest<br></strong>  # ...<br>end</pre><p>This is awesome, because now we can exercise the whole stack.</p><p>Controller tests can catch issues in controllers, views, models, view helpers and other code which is used during request processing.</p><p>As I said, controller tests bring me the most value. But what exactly do I test in them? Here are few examples.</p><p>I test that:</p><ul><li>All records have been correctly created/updated.</li><li>Emails were sent.</li><li>Jobs have been scheduled.</li><li>An action has been executed. I test it directly by side effects of the action or I just stub some object if side effects are undesirable. Example of an action: Order refund.</li></ul><p>I don’t test that:</p><ul><li>Instance variable has been assigned.</li><li>A particular template has been rendered.</li></ul><p>This is not a comprehensive list of things which I test in my controller tests, but it should give you an idea what to test.</p><p>Example:</p><pre># test/controllers/refunds_controller_test.rb</pre><pre>class RefundsControllerTest &lt; ActionDispatch::IntegrationTest<br>  test &quot;refund order&quot; do<br>    order = orders(:for_john_doe)<br>    PaymentGateway.any_instance.expects(:refund_charge)</pre><pre>    assert_enqueued_emails 1 do<br>      post refunds_url, params: { order_id: order.id }<br>    end</pre><pre>    order.reload<br>    assert order.refunded?<br>    assert_redirected_to order_path(order)<br>  end<br>end</pre><p>Controller tests are awesome because they exercise the whole stack. But this might be not enough when you depend on JavaScript which is executed on the client side. Enter system tests.</p><h4>System tests</h4><p>Systems tests are one level higher than controller tests. They test application from user’s point of view by simulating user actions via browser. This could be a headless browser (it doesn’t create a new browser window) or a real browser like Chrome, Firefox or Safari. Rails 5.1 uses Chrome by default.</p><blockquote>Btw. it is kind of cool to <a href="http://imgur.com/a/Sp6xw">watch your systems tests</a> from time to time ;).</blockquote><p>Unlike with controller tests I don’t tend to test all possible paths in system tests unless I am testing some critical component of our application.</p><p>A good example is <a href="https://memberful.com/help/general/memberful-overlay/">our checkout</a> (click on the “Test subscription” button). This is one of the most important parts of our application and it is rendered mostly on the client. Therefore we test a lot of different checkout scenarios with systems tests.</p><p>System tests are based on the <a href="https://github.com/teamcapybara/capybara">capybara gem</a> and they were added to Rails in Rails 5.1. Of course that we used them also before, we just did not call them system tests. They were usually called integration tests or feature tests. Also, before Rails 5.1 they required a special setup and installation of few gems. Fortunately this is not true anymore and you can use them straight after rails new.</p><p>If you want to see a nice system test, then check the following example from Basecamp:</p><h3>DHH on Twitter</h3><p>System tests have finally taken strong hold at @Basecamp. Can&#39;t wait for us to level-up @Rails with great defaults for it in 5.1!</p><h4>Model tests</h4><p>Model tests are useful, too. You just need to know what to test and what to NOT test.</p><p>I don’t test:</p><ul><li>Rails validations. They are already tested in Rails.</li><li>Associations. Again, I don’t want to test Rails itself.</li><li>Simple scopes.</li></ul><p>I test:</p><ul><li>Custom validations. This can be also a regular expression in the format validation.</li><li>Complicated scopes. I want to be sure that I receive records which should be returned.</li><li>Custom methods and custom attribute writers.</li></ul><p>Example:</p><pre># test/modes/user_test.rb</pre><pre>class UserTest &lt; ActiveSupport::TestCase<br>  test &quot;downcase email address&quot; do<br>    member = User.new(email: &quot;John.Doe@example.com&quot;)</pre><pre>    assert_equal &quot;john.doe@example.com&quot;, member.email<br>  end<br>end</pre><h4>Helper tests</h4><p>I love helpers and I prefer to use them instead of decorators and similar concepts. But I don’t test them too much. They are usually indirectly tested by controller tests.</p><p>However there are few helpers in our application which we test thoroughly.</p><p>For example we have a helper called subscription_description. It returns a subscription description based on current subscription state. There are 12 possible states and therefore 12 different descriptions. I want to be sure that we generate correct description for every state. Also, more importantly I want to be sure the helper doesn’t cause a HTTP 500 error because of a typo. Therefore I test it thoroughly.</p><p>Example:</p><pre>class SubscriptionHelperTest &lt; ActionView::TestCase<br>  test &quot;#subscription_description&quot; do<br>    subscription = subscriptions(:for_john_doe)<br>    subscription.update!(expires_at: &quot;2017-07-31&quot;, autorenew: true)</pre><pre>    expected_description = &quot;Renews on July 31st, 2017.&quot;<br>    actual_description = subscription_description(subscription) </pre><pre>    assert_equal expected_description, actual_description</pre><pre>    # other assertions<br>  end<br>end</pre><h4>Object tests</h4><p>From time to I need to extract logic from a controller (or somewhere else) to another object. I don’t do this often, because I don’t have issues with some logic in controllers, but when I do it I make sure that this object is thoroughly tested.</p><p>Rails doesn’t care where you put your objects. For example it can be app/models/, app/services/ or lib/some_integration/.</p><p>Let’s say I have a non-ActiveRecord model in called GiftCreator which lives in app/models/. Then its test might looks like this:</p><pre># test/models/gift_creator_test.rb</pre><pre>require &quot;test_helper&quot;</pre><pre>class GiftCreatorTest &lt; ActiveSupport::TestCase<br>  test &quot;create a gift&quot; do<br>    GiftCreator.new.do_stuff</pre><pre>    assert_stuff_is_done<br>  end<br>end</pre><h4><strong>Background job tests</strong></h4><p>I test background jobs in a similar fashion as regular objects.</p><p>Example:</p><pre># test/jobs/do_stuff_job_test.rb</pre><pre>require &quot;test_helper&quot;</pre><pre>class DoStuffJobTest &lt; ActiveJob::TestCase<br>  test &quot;do some stuff&quot; do<br>    DoStuffJob.perform_now</pre><pre>    assert_stuff_is_done<br>  end<br>end</pre><h4>Mailer tests</h4><p>Emails are critical part of our application therefore I want to be sure that our mailers don’t fail. I usually don’t test every detail of generated emails. It is enough for me to know that it works and it doesn’t fail.</p><p>Example:</p><pre># test/mailes/user_mailer_test.rb</pre><pre>require &#39;test_helper&#39;</pre><pre>class UserMailerTest &lt; ActionMailer::TestCase<br>  test &quot;welcome user&quot; do<br>    user = users(:john_doe)</pre><pre>    email = UserMailer.welcome(user)</pre><pre>    assert_equal [user.email], email.to<br>  end<br>end</pre><p>Emails are generated and delivered asynchronously from a background job. But if they weren’t, I wouldn’t probably test mailers because they would be indirectly tested by controller (and other) tests.</p><h4><strong>Test Driven Development (TDD)</strong></h4><p>TDD means that your design is driven by tests. It works like this:</p><ol><li>You write a failing test.</li><li>You write a code to make the test pass.</li><li>You refactor the code.</li></ol><p>It sounded great when I was learning Rails. But, nah. I don’t use TDD too much anymore. I don’t know what I am going to do, so how can I test it first? I still write some tests before the actual code, but usually I write my tests later. And I’m <a href="http://david.heinemeierhansson.com/2014/tdd-is-dead-long-live-testing.html">not</a> <a href="http://www.rubyfleebie.com/testing-rails-applications-in-the-life-of-a-freelancer/">alone</a>.</p><h4><strong>Testing tools</strong></h4><p>I learned Rails together with RSpec, FactoryGirl and bunch of other tools like Timecop, spork, and I can’t remember what else.</p><p>I don’t use any of these anymore. I use default Rails stack instead. That is MiniTest and database fixtures. Also, since Rails 5.1 gave us system tests I don’t need to install a single additional tool or tune my test_helper.rb anymore.</p><p>Well, kind of. I still use tools like <a href="https://github.com/vcr/vcr">VCR</a>, <a href="https://github.com/bblimke/webmock">webmock</a> or <a href="https://github.com/freerange/mocha">mocha</a> when I need to, but these aren’t the tools which are needed in every Rails application.</p><p>That’s all. This is where I ended after 4 years with Rails. I am a single developer at <a href="https://memberful.com/">Memberful</a>. If something is not working as expected, then usually I am the one to blame. Thanks to automated testing this doesn’t happen too often.</p><p><em>What is your experience with testing? Do you test your applications? Do you struggle with testing? Let me know in comments, </em><a href="https://twitter.com/patrikbona"><em>ping me on Twitter</em></a><em> or </em><a href="https://prodigious-writer-332.ck.page/51ce0c15e3"><em>subscribe to my newsletter and shoot me an email</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf150e347a6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/how-i-test-my-rails-applications-cf150e347a6b">How I test Rails applications</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you really need that fancy JavaScript framework?]]></title>
            <link>https://medium.com/patrik-on-rails/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/e6f2531f8a38</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Tue, 20 Jun 2017 15:40:33 GMT</pubDate>
            <atom:updated>2020-12-27T20:46:58.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbTm5LA73DWndujoRgQXMw.jpeg" /><figcaption>Wait, what? (<a href="https://unsplash.com/photos/O2czGO7KLag">unsplash.com</a>)</figcaption></figure><p>People are going crazy about single page applications and client side rendering. But, do we really need them?</p><p>As opposite to that, Ajax in Ruby on Rails works like this:</p><ol><li>Client send an Ajax request to the server.</li><li>Server generates new HTML, wrap it in JavaScript and send it to the client.</li><li>The JavaScript code is executed by the client and DOM modifications are applied.</li></ol><p>Sounds boring? Well, it isn’t! Continue reading to learn about <a href="https://signalvnoise.com/posts/3697-server-generated-javascript-responses">Server-generated JavaScript Responses</a> and see what you can do with this simple but powerful technique in <a href="#8ade">real world examples</a>.</p><p>Rails makes Ajax development experience seamless. In order to understand how it works, we need to know how it’s particular pieces work and how they all fit together.</p><p><strong>rails-ujs</strong></p><p>rails-ujs is an unobtrusive JavaScript adapter. Unobtrusive means, that you don’t need to write any JavaScript to create behaviour which is handled by JavaScript. For example you can create forms submitted via Ajax and you don’t need to write any JavaScript in order to do that.</p><p>See the following example:</p><pre>&lt;form action=&quot;/users&quot; <strong>data-remote=&quot;true&quot;</strong> method=&quot;post&quot;&gt;<br>  ...<br>&lt;/form&gt;</pre><p>data-remote=&quot;true&quot; is the unobtrusive part. When you add it to your form, rails-ujs will catch the form submit action, submit the form via Ajax and automatically execute JavaScript code received in the response.</p><p>We call such responses “Server-generated JavaScript Responses”. Or in short SJR. You can read about them in <a href="https://signalvnoise.com/posts/3697-server-generated-javascript-responses">this post</a> from <a href="https://medium.com/u/54bcbf647830">DHH</a>.</p><blockquote>rails-ujs does much more than just sending Ajax requests. Check out my <a href="https://m.patrikonrails.com/a-definitive-guide-to-railss-unobtrusive-javascript-adapter-ef13bd047fff">definitive guide to rails-ujs</a> to learn more.</blockquote><p><strong>Turbolinks</strong></p><p><a href="https://github.com/turbolinks/turbolinks">Turbolinks</a> is unobtrusive, too. You include it in your project, it binds to the click action on all links and then automatically submit them via Ajax once they are clicked.</p><p>But unlike rails-ujs, Turbolinks expects an HTML response. Once it arrives, Turbolinks replaces &lt;body&gt; of your page with &lt;body&gt; from the response.</p><p>This is faster than full page reload because browser doesn’t need to request and process all JavaScript and CSS files again.</p><p><strong>Rails + rails-ujs + Turbolinks</strong></p><p>Both, rail-ujs and Turbolinks are included in Rails by default. They work very nicely together. See the following example.</p><p>View:</p><pre># app/views/users/_form.html.erb</pre><pre>&lt;%= form_with model: @user do |form| %&gt;<br>  ...<br>&lt;% end %&gt;</pre><p>This generates the following HTML:</p><pre>&lt;form action=&quot;/users&quot; data-remote=&quot;true&quot; method=&quot;post&quot;&gt;<br>  ...<br>&lt;/form&gt;</pre><p>Notice the data-remote=&quot;true&quot; part. It was added automatically by form_with.</p><blockquote>form_with is a new Rails 5.1’s addition which is going to replace form_tag and form_for. <a href="https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a">Learn more about it in my previous post</a>.</blockquote><p>When you submit this form, then rails-ujs will submit it as an Ajax request and it will expect JavaScript code in the response.</p><p>Controller:</p><pre># app/controllers/users_controller.rb</pre><pre>class UsersController &lt; ApplicationController<br>  def create<br>    @user = User.new(user_params)</pre><pre>    if @user.create<br>      redirect_to user_path(@user)<br>    end<br>  end<br>end</pre><p>When a user is created, then we want to redirect client to the user page. We can’t use standard redirects, because they don’t work with JavaScript requests.</p><p>Fortunately <a href="https://github.com/turbolinks/turbolinks-rails/blob/master/lib/turbolinks/redirection.rb">turbolinks-rails</a> got us covered and</p><pre>redirect_to user_path(@user)</pre><p>generates the following JavaScript code:</p><pre>Turbolinks.clearCache()<br>Turbolinks.visit(&quot;http://web.dev/users/1&quot;,{&quot;action&quot;:&quot;replace&quot;})</pre><p>This code is executed by rails-ujs and the current page is replaced by the page from http://web.dev/users/1.</p><p>So, the happy path, when there are no validation errors is working. But what happens when the user model isn’t valid? Then the controller will render a JavaScript template for the create action:</p><pre># app/views/users/create.js.erb (jQuery version)</pre><pre>$(&quot;form&quot;).replaceWith(&quot;&lt;%= j render &quot;form&quot; %&gt;&quot;);</pre><p>It’s just one line of code, but the code itself might be not obvious so let’s deconstruct it.</p><p>render &quot;form&quot; will generate HTML for our form.</p><p>j is an alias for <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript">escape_javascript</a> and it will escape our HTML so we can use it in the JavaScript response.</p><p>$(&quot;form&quot;).replaceWith(...) will replace the old HTML form code with the new one which should contain validation errors.</p><p>To put it all together, we generated a new HTML code and wrapped it in the JavaScript code which replaces the old form with the new one.</p><p><strong>Summary</strong></p><p>We just learned how to do two things with Server-generated JavaScript Responses:</p><ol><li>Perform Ajax redirects with Turbolinks.</li><li>Modify DOM with a response from the server.</li></ol><p>It doesn’t sound so exciting, right? Well, you can do quite a lot with this simple technique. This brings us to the next section.</p><p><strong>Real-world examples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*q1VkEKkj_iIbZqKcISkv0Q.gif" /><figcaption>Sending test emails.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*oNby0m8-yO4rLaKTFfiv6Q.gif" /><figcaption>Subscription management.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*3uBT-7eLQUk-YBPj9nJEsg.gif" /><figcaption>Modals!</figcaption></figure><p>So, what do you say? Maybe you really don’t need that fancy JavaScript framework after all.</p><p><strong>SJR pros</strong></p><ul><li>No duplication of logic, because all logic lives on the server.</li><li>No duplication of views, because all views live on the server.</li><li>Simple, but powerful technique which allows us to create a better user experience with a very little overhead.</li></ul><p><strong>SJR cons</strong></p><ul><li>Not suitable for complex UI interactions.</li></ul><p><strong>Conclusion</strong></p><p>I’m not saying that there is no place for single page applications. But I really think that they are overrated and people often use them even if they don’t need to. What the heck. I believe that vast majority of web applications can live without them and that they create more problems than they solve.</p><p>If you are learning to program web applications, and you are not sure which JavaScript framework you should learn, then maybe <em>none </em>is the answer. Just learn a full-stack framework like Ruby on Rails and you will be able to do much more with less effort.</p><p><em>Hey you! Please consider </em><a href="https://prodigious-writer-332.ck.page/51ce0c15e3"><em>subscribing to my newsletter</em></a><em> if you enjoyed this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f2531f8a38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38">Do you really need that fancy JavaScript framework?</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 5.1's form_with vs. form_tag vs. form_for]]></title>
            <link>https://medium.com/patrik-on-rails/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a?source=rss----4e5d1b29b51c---4</link>
            <guid isPermaLink="false">https://medium.com/p/3a5f72a8c78a</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Patrik Bóna]]></dc:creator>
            <pubDate>Sat, 10 Jun 2017 19:13:46 GMT</pubDate>
            <atom:updated>2018-03-08T21:18:11.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFZId_tlC-8I4okYLFQYdA.jpeg" /><figcaption>form_tag, form_for, form_with… Which one should I use? (<a href="https://pixabay.com/en/choose-the-right-direction-1536336/">pixabay.com</a>)</figcaption></figure><p>form_tag and form_for are soft deprecated and they will be replaced by form_with in the future. If you want to know more about form_with then you can peruse the original <a href="https://github.com/rails/rails/issues/25197">DHH’s proposal</a>, check the <a href="https://github.com/rails/rails/pull/26976/files">pull request</a> in which it was implemented, check the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with">API documentation</a> and play with it in a test project.</p><p>Or, continue reading this post in which I explain differences between form_tag, form_for and form_with with code samples.</p><p><strong>One syntax to rule them all</strong></p><p>Previously when you wanted to create a form, but you did not have an underlying model for it, then you used form_tag.</p><pre>&lt;%= form_tag users_path do %&gt;<br>  &lt;%= <strong>text_field_tag</strong> :email %&gt;<br>  &lt;%= <strong>submit_tag</strong> %&gt;<br>&lt;% end %&gt;</pre><p>When you had a model, then you used form_for.</p><pre>&lt;%= form_for @user do <strong>|form|</strong> %&gt;<br>  &lt;%= <strong>form.text_field</strong> :email %&gt;<br>  &lt;%= <strong>form.submit</strong> %&gt;<br>&lt;% end %&gt;</pre><p>As you can see, we use form builder field helpers with form_for but we don’t do that with form_tag. So the syntax for both forms is different.</p><p>This isn’t the case with form_with, because we use form builder all the time.</p><p>form_with without a model:</p><pre>&lt;%= form_with <strong>url: users_path</strong> do |form| %&gt;<br>  &lt;%= form.text_field :email %&gt;<br>  &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p>form_with with a model:</p><pre>&lt;%= form_with <strong>model: @user</strong> do |form| %&gt;<br>  &lt;%= form.text_field :email %&gt;<br>  &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p>When you set themodel argument then scope and url are automatically derived from it. This behaviour is similar to form_for.</p><p><strong>Automatic ids and classes are gone</strong></p><p>form_tag and form_for generate automatic ids for form fields. form_for does it also for forms.</p><pre>&lt;%= form_for User.new do |form| %&gt;<br>  &lt;%= form.text_field :email %&gt;<br>&lt;% end %&gt;</pre><p>Generates:</p><pre>&lt;form <strong>class=&quot;new_user&quot; id=&quot;new_user&quot;</strong> action=&quot;/users&quot; ...&gt;<br>  ...<br>  &lt;input type=&quot;text&quot; name=&quot;user[email]&quot; <strong>id=&quot;user_email&quot;</strong> /&gt;<br>&lt;/form&gt;</pre><p>With form_with you have to specify all of your ids and classes manually:</p><pre>&lt;%= form_with model: @user do |form| %&gt;<br>  &lt;%= form.text_field :name %&gt;<br>  &lt;%= form.text_field :email, <strong>id: :email</strong>, <strong>class: :email</strong> %&gt;<br>&lt;% end %&gt;</pre><p>Generates:</p><pre>&lt;form action=&quot;/users&quot; ...&gt;<br>  ...<br>  &lt;input type=&quot;text&quot; name=&quot;user[name]&quot; /&gt;<br>  &lt;input <strong>id=&quot;email&quot; class=&quot;email&quot;</strong> type=&quot;text&quot; name=&quot;user[email]&quot; /&gt;  &lt;/form&gt;</pre><p>Do not forget to specify ids for form fields if you want to make labels work.</p><pre>&lt;%= form_with model: @user do |form| %&gt;<br>  &lt;%= <strong>form.label :name</strong> %&gt;<br>  &lt;%= form.text_field :name, <strong>id: :user_name</strong> %&gt;<br>&lt;% end %&gt;</pre><blockquote>Update: <a href="https://github.com/rails/rails/commit/d3893ec38ec61282c2598b01a298124356d6b35a">form_with will automatically generate ids since Rails 5.2</a> so you will not need to manually specify them anymore.</blockquote><p><strong>Form id and class attributes aren’t wrapped anymore</strong></p><p>Before:</p><pre>&lt;%= <strong>form_for</strong> @user, <strong>html: { id: :custom_id, class: :custom_class }</strong> do |form| %&gt;<br>&lt;% end %&gt;</pre><p>After:</p><pre>&lt;%= <strong>form_with</strong> model: @user, <strong>id: :custom_id, class: :custom_class</strong> do |form| %&gt;<br>&lt;% end %&gt;</pre><p><strong>Form fields don’t have to correspond to model attributes</strong></p><p>Before:</p><pre>&lt;%= <strong>form_for</strong> @user do |form| %&gt;<br>  &lt;%= form.text_field :email %&gt;<br>  &lt;%= <strong>check_box_tag</strong> :send_welcome_email %&gt;<br>&lt;% end %&gt;</pre><p>After:</p><pre>&lt;%= <strong>form_with</strong> model: @user, local: true do |form| %&gt;<br>  &lt;%= form.text_field :email %&gt;<br>  &lt;%= <strong>form.check_box</strong> :send_welcome_email %&gt;<br>  &lt;%= form.submit %&gt;<br>&lt;% end %&gt;</pre><p>Please note, that send_welcome_email will be scoped to user in controller parameters in the latter example:</p><pre>params[:user][:send_welcome_email]</pre><p>Therefore I would probably still use check_box_tag instead of form.check_box if I needed to.</p><p><strong>All forms are remote by default</strong></p><p>This change is the most exciting to me. All forms generated by form_with will be submitted by an XHR (Ajax) request by default. There is no need to specify remote: true as you have to with form_tag and form_for.</p><p>I like this feature, because it sends a message. Thanks to Turbolinks, (almost) all GET requests are XHR requests by default. And thanks to form_with this can become a reality for forms, too. You just need to do a little bit of work (create a JavaScript response template) and you can eliminate all full page refreshes.</p><p>However, if you want to disable remote forms then you can do it with local: true.</p><pre>&lt;%= form_with model: @user, <strong>local: true</strong> %&gt;<br>&lt;% end %&gt;</pre><blockquote>Don’t you know how to process remote forms in your application? <a href="https://m.patrikonrails.com/do-you-really-need-that-fancy-javascript-framework-e6f2531f8a38">Then check this post to learn more.</a></blockquote><p><strong>Let’s use form_with since now and never look back!</strong></p><p>I did not cover everything in this post, but it should be enough to get you started with form_with so you don’t have to use form_tag and form_for anymore (they will be removed anyway). Also, read <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with">the documentation for </a><a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_with">form_with</a>.</p><p><em>Hey stranger! I hope that you enjoyed this post. Now </em><a href="http://www.ajaxonrails.com/"><em>check out my free course about Ajax on Rails</em></a><em>! Thanks </em>🤩<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a5f72a8c78a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/patrik-on-rails/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a">Rails 5.1&#39;s form_with vs. form_tag vs. form_for</a> was originally published in <a href="https://medium.com/patrik-on-rails">Patrik on Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>