[Ruby] If no HTTP method is specified, the browser requests GET.

1 minute read

environment

・Rails 6.0.3.2 ・Mysql Ver 14.14 Distrib 5.6.47 ・OSX10.15

Introduction

When creating a web application for the first time with Rails, when I used form_with or link_to, I was suspicious that route was working even though there was no HTTP method specified.

What is routing

It is responsible for receiving the URI Pattern and the HTTP method and specifying which action to take. Therefore, it is necessary to specify the URI Pattern and the HTTP method on the browser side.

For example

Description that a certain action moves when you press the detail button (Prefix is here)

<%= link_to'details', tweet_path(tweet.id), method: :get %>

Or (this is URI Pattern)

<%= link_to'delete', "/tweets/#{tweet.id}", method: :delete %>

Like method:, HTTP method and URI Pattern are specified.

[Main subject] When HTTP method is not specified

Specifically, the following description


<%= link_to'detail', tweet_path(tweet.id) %>

Compared to the above example, it works fine without method: :get.

that? Why don’t you specify HTTP method? ? ?

As a beginner, why does it work even though there is no specification? It was a moment when I didn’t understand the routing rules. .. ..

Conclusion

If you don’t specify an HTTP method, the browser will send a GET request to the server by default! It’s just a browser regardless of Rails routing. (*It was corrected in the comments.)

So even if you don’t specify it, the browser will send the URI Pattern and the HTTP method, and some action will work! !!

As a beginner, I didn’t know that it would work even if it was not specified.

reference

Rails routing ・Https://railsguides.jp/routing.html