0
0

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.

繰り返し処理の中で部分的にサイズを変更する

Last updated at Posted at 2020-12-09

目標

下記のように繰り返し処理(each文)の、先頭だけ画像サイズを大きく表示したい
スクリーンショット 2020-12-10 5.09.30.png

開発環境

・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 %>
# 省略

下記の様に同じ大きさで並びます
スクリーンショット 2020-12-10 4.58.51.png

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/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?