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

【ruby】ビュー内で<% i += 1 %>など書かずにeach.with_indexで書く方法

Last updated at Posted at 2020-04-16

経緯

ランキングを表すビューを書いてるときに以下のように直接コード内に
AUTO_INCREMENTになるように(整数値が1ずつ増えていく)
i+=1と設定していました。

app/views/ranks/_rank.html.erb
<% i = 1 %>
<% models.each do |model| %>
  <tr>
    <td><p><%= i %></p></td>
    <!--(省略) -->
  </tr>
  <% i += 1 %>
<% end %>

このままでは見た目があまりきれいじゃないです。

解決方法

each.with_indexを使います。

app/views/ranks/_rank.html.erb
<% models.each.with_index(1) do |model, i| %>
  <tr>
    <td><p><%= i %></p></td>
    <!--(省略) -->
  </tr>
<% end %>

これでできました。
この場合はブロック変数のiがオートインクリメントになります。
そして、each.with_indexの後ろにある(1)はスタートの番号を表しています。
1,2,3・・・と増えていきます。

こんな感じになります。
スクリーンショット 2020-04-16 15.13.53.png

参考

https://qiita.com/gestalt/items/d2c663b4be524581747e
https://shinkufencer.hateblo.jp/entry/2019/07/19/000000

2
1
2

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