LoginSignup
84
86

More than 5 years have passed since last update.

link_to の引数と展開の違いまとめ

Last updated at Posted at 2013-01-11

いつもわからなくなるのでまとめとく。

▼基本 コントローラやアクション、IDなど予約パラメータやルート定義にあるものはURLに含まれる
<%= link_to "TEST1-1", controller:"product", action:"edit" %>
<%= link_to "TEST1-2", controller:"product", action:"edit", id: 1 %>

<a href="/product/edit">TEST1-1</a>
<a href="/product/edit/1">TEST1-2</a>

-
▼第2引数をハッシュにすればURL情報であることを明示でき、また第3引数が確実にhtml属性になる。
「ハッシュの中のid」と「外のid」の扱いに注目。
<%= link_to "TEST2-1",{controller:"product", action:"edit"}, id:"title" %>
<%= link_to "TEST2-2",{controller:"product", action:"edit", id:3}, id:"title" %>

<a href="/product/edit" id="title">TEST2-1</a>
<a href="/product/edit/3" id="title">TEST2-2</a>

第2引数の中にある予約パラメータ以外のもの(book_author)は、クエリとして渡される。
<%= link_to "TEST2-3",{controller:"product", action:"edit",id:3, book_author:"Bob"}, id:"title" %>

<a href="/product/edit/3?book_author=Bob" id="title">TEST2-3</a>

-

▼第3引数もちゃんとハッシュにしたほうがわかりやすい。
<%= link_to "TEST3",{controller:"product", action:"edit"}, {id:"title", class:"top"} %>

<a href="/product/edit" id="title">TEST3</a>

-
▼ハッシュにした場合、第3引数より後は無視される。
<%= link_to "TEST4",{controller: "product", action: "edit"}, {id: 1, class: "top"},{width: 100, height: 200} %>

<a href="/product/edit" class="top" id="1">TEST4</a>

84
86
3

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
84
86