目標
下記のように繰り返し処理(each文)の、先頭だけ画像サイズを大きく表示したい
開発環境
・Ruby 2.5.7
・Rails 5.2.4.4
・macOS Catalina 10.15.7
・refile
前提
・refileで画像投稿機能実装済み
・route.rbでのルーティング、モデル間のアソシエーションは実装済み
・親モデルであるPersonモデルと画像投稿用のportraitモデルは1:Nの関係
普通の繰り返し処理
(※Personは親モデル。Personのshowページでportraitの投稿機能を実装しています)
show.html.erb
# 省略
<% @person.portraits.each do |portrait| %>
<%= attachment_image_tag portrait, :image, :fill, 100, 100 %>
<% end %>
# 省略
if文を使い、最初の処理だけ画像を大きくする
下記の様に[0]と指定すると目標で提示した画像の様に、1番目だけ大きくすることが出来ます。
show.html.erb
# 省略
<% @person.portraits.each do |portrait| %>
<% if @person.portraits[0] == portrait %>
<%= attachment_image_tag portrait, :image, :fill, 130, 130 %>
<% else %>
<%= attachment_image_tag portrait, :image, :fill, 100, 100 %>
<% end %>
<% end %>
# 省略
今回変更箇所は1番目のサイズだけですが、条件を変えて色々応用できますね!
使用イラスト
かわいいフリー素材集いらすとや
https://www.irasutoya.com/