I'm using Rails 6. I have a route that defines a get request:
namespace :admin do
get '/machines/search', to: 'machines#search', as: 'search_machines'
end
Then, I have a form_with
that sets the url
to the route
. When the form is loaded, the HTML that's generated for the form contains a method="post"
instead of method="get"
which is what I would've expected since the route is a GET request and not a POST. I can add the method: "get"
parameter to the form_with
and this fixes the issue but I don't understand why Rails didn't pick up the correct method initially.
<%= form_with url: admin_search_machines_path() do |i| %>
<%= i.text_field :q, placeholder: "Search", autocomplete: "off", class: "debounce-form-submit form-control" %>
<% end %>
According to the documentation
form_with
does default toPOST
ifmethod
is not specified. Which is not 100% correct, as it will switch toPATCH
(via hidden field trick) if the model is persisted (source).Up to today, the code does not look at the route itself to specify the
method
.I think the (backwards incompatible) automagic you suggest is not totally off, though. You might ask about that in the rubyonrails forums and get feedback whether this would be a welcomed change. Personally, I never expected it to inspect the route. Also, you might have the same route with
post
andget
methods, which would make lookup more involved than what meets the eye on first sight.