DEV Community

dianakw8591
dianakw8591

Posted on

3 2

form_with without JS

Last week I was working on a web app to link condition reports and photos with snowpack data from the date and location of the report. The app was built entirely with Ruby on Rails, and I ran into a bug when I tried to use a search form built with form_with. The generic search form solution from RailsGuides seemed like it should work great. Working from the generic form, I got to this point:

<%= form_with(url: "/search", method: "get") do %>
    <%= label_tag("Choose locations:") %>
    <%= collection_select(:location, :id, Location.all, :id, :name) %><br>
    <%= label_tag(:min, "Minimum Snow Depth (in):") %>
    <%= number_field_tag(:min) %><br>
    <%= label_tag(:max, "Maximum Snow Depth (in):") %>
    <%= number_field_tag(:max) %><br>
    <%= submit_tag("Search Posts") %>
<% end %>

Having used form_for and form_tag in the past, the syntax looked familiar, but when I submitted a search, nothing happened! I knew I was hitting the right route and my log even said that it was rendering the results page. But no new page was rendered.

Enter the :local option. By default, form_with submits are XMLHttpRequest (XHR) objects - put another way, they are AJAX requests. The main benefit of AJAX (Asynchronous JavaScript And XML) is that it communicates with the server and renders new data without a full page refresh. The first line of html generated from my original form_with with default options looks like this:

<form accept-charset="UTF-8" action="/search" data-remote="true" method="get">

The data-remote="true" bit tells Rails to submit the data as an AJAX request. But without Javascript in the mix, this default option was causing problems.

In order to disable the default remote submits, add local: true as an option to the form, like so:

<%= form_with(url: "/search", method: "get", local: true) do %>

After that, my results page rendered as expected.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (2)

Collapse
 
molly profile image
Molly Struve (she/her) β€’

Googled "rails form_with dont use javascript" landed here, couldn't be more perfect. Thanks for the help!!!

Collapse
 
ben profile image
Ben Halpern β€’

Nice heads up

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay