0
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

リンクを作成する

サイトを作成する際に別記事やサイトへ移動する方法を記録します。

下記2つの方法を使用してリンクを作成します。
①HTMLのaを使用する場合
②link_toを使用する場合

具体例

①HTMLのaを使用する場合

(1)文字列にリンクを行う場合

<a href="URL">文字列</a>

(2)画像にリンクを付ける場合

<a href="URL"><img src="assets/画像ファイル名"></a>

②link_toを使用する場合
(1)文字列にリンクを行う場合
⇒表示したい文字を一緒に作ることができ、移動先も設定する

<%= link_to "表示したい文字列", root_path %>
<%= link_to("表示したい文字列", "URL") %>

(2)画像にリンクを付ける場合
⇒画像を押したときにリンク先に行く場合は以下のように、do_endの中に画像データを指定する。

<%= link_to [root_path] do %> <%= image_tag '画像ファイル名' %> <% end %>

※<% end %>を忘れやすいので注意

実際の使用例 紹介

下記は配列を用い、テーブルとして表記した場合の実際例です。
テーブルで一覧を表記している時に項目ごとにリンクを付ける方法です。
引数等は参考程度にご覧ください。

              </thead>
                    <% @books.each do |book| %>
                  <tbody>
                    <td><%= link_to user_path(book.user.id) do %>
                    <%= attachment_image_tag book.user, :profile_image, :fill, 100, 100, format: 'jpeg', fallback: "no_image.jpg", size:'100x100'  %>
                    <% end %> </td>
                    <td><%= link_to book.title,book_path(book)%></td>
                    <td><%= book.body %></td>
                    <% end %>
                 </tbody>
            </table>

この中で特に難しかった点(下記)を解説します。
実際にbook.userの方の1つずつのimageを算出する。その際に表示画像の大きさを指定しています。またfallbackというもので画像がない場合にはno_image.jpgを表示するように記載しています。

図8.png
※上記の記載名はサンプルです。また画像もリンクになっており、画像・文字がリンクになっている。またリンク先も指定することができる。

【リンクの設定した画像のサイズ感を設定する方法】

<%= attachment_image_tag book.user, :profile_image, :fill, 100, 100, format: 'jpeg', fallback: "no_image.jpg", size:'100x100'  %>

・size: "横幅数値x高さ数値"
・no_image.jpg:これはアプリケーションに直接入れ込んで実装
(app/assets/imagesの中に入れました)

リンクにボタンを実装する場合 実例(Bootstrap導入時に実装可能)

リンクボタンを作成しそこにリンクを張り付ける場合の実例を記載しています。

以下の内容で注目すべき点は、class:という記載からになります。
class:と記載することでbtnというボタンを実装できます。また今回はアイコンも使用しているためこのような仕様になっています。

<%= link_to edit_user_path(current_user) ,class: "btn btn-outline-secondary btn-block fas fa-user-cog" do %>
<% end %>

※<% end %>を忘れやすいので注意

以下の赤枠の内容を表示しています。

図5.png

0
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
0
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?