Rails はいろいろといい感じにやってくれるので便利だけど、理解しないままなんとなく使ってしまっているところが多いので整理した。
link_to
link_to
は、リンク先を指示するヘルパーメソッド。
書き方
ERB
<%= link_to リンクテキスト, パス[, オプション] %>
slim
= link_to リンクテキスト, パス[, オプション]
以下のような<a>
タグが生成される。
<a href="パス">リンクテキスト</a>
パスの書き方
例
<%= link_to "Profile", profile_path(@profile) %> # => <a href="/profiles/1">Profile</a>
show
/update
/destroy
アクションの場合は、パスをオブジェクト名だけで指定することができる。profile_path(@profile)
と書かずに@profile
だけで OK。
上の例(show
)だと、次のように書ける。
<%= link_to "Profile", @profile %> # => <a href="/profiles/1">Profile</a>
edit などの場合は省略できないので、次のようになる。
<%= link_to "Edit Profile", edit_profile_path(@profile) %>
(参考)link_toメソッドを使ったリンクの作成 - Ruby on Rails入門
ブロックを渡す書き方
link_to
には、ブロックを渡すこともできる。
ERB
<%= link_to パス[, オプション] do %> リンクテキストや画像など <% end %>
slim
= link_to パス[, オプション] do
= リンクテキストや画像など
画像にリンクを張る例。
slim
= link_to image_tag(company.logo_url, alt: company.name, class: "company-icon"), company / こう書ける = link_to company do = image_tag company.logo_url, alt: company.name, class: "company-icon"