1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

link_toの適用範囲を広げる

Posted at

link_toとは

名前の通りリンクを生成するRailsメソッドである。
link_toは初期HTTPメソッドがGETのため、扱うメソッドによってはオプションで指定する必要がある。

基本的には下記の様な記述で利用する

# 公式ドキュメント
link_to リンクテキスト, パス[,オプション, HTML属性 or イベント属性])

# 実用例
link_to 'トップページ', root_path
# devise導入によるセッションでの例
link_to '削除', destroy_user_session_path, method: :delete

これによりリンクテキスト部分が指定したパスへのリンクとして表示される様になる。
またリンクテキスト部分には画像も使う事ができる。

改善したい点

この使い方だけだとショッピングサイトの様に一度に画像、商品名などを表示する際に
一つ一つにlink_toを記述する必要があるため面倒であり管理が煩雑になってしまう

一括でlink_toを適用する

上記の問題を解決するのに用いるのがdo~endによるブロックである。

link_to item_path, do
  #画像や文字列など
end

上記の様にする事でdo ~ endまでをブロックとしパスを渡す事で
ブロック内の要素全てにリンク要素がつく様になります。

まとめ

煩雑さを取り払う事ができた。
注意点としては非同期通信などの要素の配置に気をつけないと
結局一つ一つに適用する必要が出てくるためデザイン面も気をつけたい

1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?