LoginSignup
3
1

More than 1 year has passed since last update.

link_toとform_tagのデフォルトメソッドについて。

Last updated at Posted at 2022-04-13

結論

link_to メソッド -> GETメソッドがデフォルト。
form_tagメソッド -> POSTメソッドがデフォルト

link_toメソッド

下記のようなroutes.rbメソッド違いの同じURLが存在する時、postメソッドのURLにリンクするためには{method:"post"}が必要です。({method:"post"}がないと、getメソッドのパースにリンクされてしまう。)

routes.rb
post "posts/:id/destroy" => "..."
get "posts/:id/destroy" => "..."

show.html.erb
<%= link_to (”destroy",”/posts/#{@post.id}/destroy),{method:"post"}) %>

form_tagメソッド

form_tagメソッドですと、post "posts/:id/destroy" => "..."にデータを渡すためには、引数にmethodを指定する必要はありません。
下記のコードで渡すことができます。

<%= form_tag('/posts/#{@post.id}/destroy') do %>
  <div><%= submit_tag 'Save' %></div>
<% end %>

なぜ?

link_toメソッドもform_tagメソッドも同じくURLを扱うメソッドなのに、なんでlink_toのみ{method:"post"}が必要かが、学習する際に、疑問でした。
それで、railsのgit hubを参照すると、

link_to メソッドの説明

==== Options
method: symbol of HTTP verb ...
...
# Note that if the user has JavaScript disabled, the request will fall back
# to using GET ....

methodのオプションでJavaScirptが無効になっている場合は、Getメソッドを使用することになる。と書いてます。

form_tagメソッドの説明

The method for the form defaults to POST.
...
:method The method to use when submitting the form, usually either "get" or "post".
# If "patch", "put", "delete", or another verb is used, a hidden input with name _method
# is added to simulate the verb over post.

formのデフォルトメソッドはPOSTだと書いています。
そして、メソッドがサブミットするときはpostが:methodオプションのhiddenインプットとして追加されるとなってます。

終わりに

学習をしていく上で'なぜ?'と思うときは、まずその言語のソースコードを読んでみることが大事だと教わりました。
今回はメソッドのデフォルトがGETやPOSTになっているからこういう動きをします!という簡単な内容でしたが、
ブログの検索しても出なかった内容が、ソースコードを読むことですぐに解決できましたので、ソースコードを読む習慣が大事だと実感したいい経験でした。

読んでくださってありがとうございました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1