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.

[Rails]ランキング機能に王冠マークつける方法

Last updated at Posted at 2020-12-19

今回はランキングに王冠マークをつける方法を書いていきたいと思います。

前提

・ランキング機能を実装していること。以下記事を参考させていただきました。
以下に記載するviewのメソッドなどは以下の記事を参照しておりますのでご了承ください。
https://qiita.com/mitsumitsu1128/items/18fa5e49a27e727f00b4
・Font-Awesome6が使用できる状態にして置くこと。

王様マークをつける

rank.html.erb
<table>
  <thead>
    <tr>
      <th class= "text-center">順位</th>
      <th class= "text-center">Note</th>
    </tr>
  </thead>
  <tbody>
    <% @all_ranks.each.with_index(1) do |note, index| %>
      <tr>
        <td class="text-center">
          <% case index when 1 %>
            <i class="fas fa-crown" style='color: gold;'></i>
          <% when 2 %>
            <i class="fas fa-crown" style='color: silver;'></i>
          <% when 3 %>
            <i class="fas fa-crown" style='color: orange;'></i>
          <% else %>
            <%= index %>
          <% end %>
        </td>
        <td class="text-center">
          <%= link_to user_note_path(note) do %>
            <%= note.name %>
          <% end %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>     

説明

<% case index when 1 %>
これはrubyのcase文です。「if」文では複数の条件式を組み合わせて複雑な分岐を行う事ができますが、一つの値に対して複数の候補の中で一致するものを探すような場合には「case」文を使用すると便利です。例は以下の通りです。

case 対象オブジェクト
when 値1
  値1と一致する場合に行う処理
when 値2
  値2と一致する場合に行う処理
when 値3
  値3と一致する場合に行う処理
else
  どの値にも一致しない場合に行う処理
end

.with_index(1)を使用することで1から順番に数字を出力してるのでこれに対して1の時に金の王冠、2の時に銀の王冠、3の時銅の王冠のように case文で実装しております。

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?