25
32

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 5 years have passed since last update.

【Rails】リンクを作成する

Last updated at Posted at 2018-08-08

HTMLタグを使う

文字列にリンク付け

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

画像にリンク付け

画像表示の詳細はこちらの記事を参考に。

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

link_toを使う

文字列にリンク付け

Rubyのlink_toメソッドを用いてリンクを作成する。

<%= link_to "表示したい文字列", root_path名 %>
<%= link_to("表示したい文字列", "URL") %>
index.html.erb
<h1>Members</h1>
<ul>
	<% @members.each do |member| %>
		<%= link_to member.name, member_path(member.id) %><br>
	<% end %>
    <%= link_to("Home", "/momocloapp") %>
</ul>

画像にリンク付け

画像をクリックするとリンク先に飛ぶようにする。

<%= link_to [root_path名] do %> <%= image_tag '画像ファイル名' %> <% end %>
index.html.erb
<h1>Members</h1>
<ul>
	<div class="member">
		<%= link_to member_path(1) do %>
	 		<%= image_tag 'kanako.png' %>
		<% end %>
	</div>
</ul>

root_path名の例

URL root_path名
/ root_path
/members members_path
/member/1 members_path(1)

リンクを押したあとも文字色を変えない

リンク付けした文字列をクリックすると、その文字列の色はクリック済みであることがわかりやすいように変わる。
スクリーンショット 2018-08-08 23.18.19.png

もしクリックした後も文字列の色を変えたくない場合は、対応するCSSファイルのbody部に以下の1行を追加する。

a:visited { color:white; text-decoration:none }

下の例では、
訪問前のリンク・訪問後のリンク・マウスカーソルを上に乗せたとき・クリックした瞬間
それぞれのリンク部の色を白に指定してある。

members.scss
 body {
     background-color: #FAE5F6;
     a:link {color:white; text-decoration:none }
  	 a:visited { color:white; text-decoration:none }
  	 a:hover { color:white; text-decoration:none }
  	 a:active { color:white; text-decoration:none }
 }
25
32
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
25
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?