loading...

form_with without JS

dianakw8591 profile image dianakw8591 ・2 min read

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.

Posted on by:

dianakw8591 profile

dianakw8591

@dianakw8591

Rock climber turned coder.

Discussion

markdown guide
 

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