画像やタイトルなどいろいろな要素を同時にリンクさせたいとき、link_toメソッドに do ~ end のブロックを渡し、それらを each で全件表示させたいときのメモです。
Controllers
コントローラーでArticleを全件表示します。
app/controllers/top_controller.rb
1 2 3 4 5 |
class TopController < ApplicationController def index @articles = Article.all end end |
Views
each do ~ end で全件表示し、その中で link_to を書きますが、 そこに do ~ end のブロックを使います。これで link_to do ~ end の中の要素は同時にリンクできるようになりました。
app/views/top/index.html.erb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<% @articles.each do |article| %> <ul> <li> <%= link_to article_path(article), class: 'hoge' do %> <% if article.image? %> <%= image_tag article.image.to_s %> <% else %> <%= image_tag 'no_image.png' %> <% end %> <h4><%= article.title %></h4> <p><%= article.sentence %></p> <% end %> </li> </ul> <% end %> |
参考サイト
http://railsdoc.com/references/link_to
以上、link_toに関するメモでした!