LoginSignup
5
0

More than 1 year has passed since last update.

シンプル星評価機能 ~ Rails

Last updated at Posted at 2021-06-28

星評価機能

このページでは投稿の星評価機能をシンプルに実装します。

image.png

1.integer型のstarカラム追加
2.for文で番号の数だけ☆を表示
3.CSSで簡単にデザインを実装

投稿用のテーブルはtweetsテーブルを例に挙げています。

1.integer型のstarカラム追加

cmd
$ rails g migration AddStarToTweets star:integer
$ rails db:migrate

2.for文で番号の数だけ★を表示

※過去に投稿していたレコードのstarカラムはnilになっているので、for文で扱うときにエラーが起こります。これを回避するために一旦過去レコードを削除しましょう。

cmd
$ rails c
> Tweet.destroy_all
> exit

次に、新規投稿ページと一覧表示ページを以下のように記述します。

views/new.html.erb
<%= form_for(@tweet, :url => { controller:'tweets', action:'create'})do |f| %>

<!-- 中略 -->

<div class="star-field">
    <input id="star5" type="radio" name="tweet[star]" value="5" />
    <label for="star5"></label>
    <input id="star4" type="radio" name="tweet[star]" value="4" />
    <label for="star4"></label>
    <input id="star3" type="radio" name="tweet[star]" value="3" />
    <label for="star3"></label>
    <input id="star2" type="radio" name="tweet[star]" value="2" />
    <label for="star2"></label>
    <input id="star1" type="radio" name="tweet[star]" value="1" />
    <label for="star1"></label>
</div>

<!-- 中略 -->

<% end %>

ラジオボタンを利用しています。どれか一つが選択されたら、該当の数字が送られます。

views/tweets/index.html.erb
  <% @tweets.each do |t| %>

    <!-- 中略 -->

    <div class="star">
      <% if t.star? %>
        <% for i in 1..t.star do %><% end %>
      <% end %>
    </div>

  <!-- 中略 -->

  <% end %>
</div>

もしt.starが存在していたら、t.starの数だけfor文を回して★を表示しています。

3.CSSで簡単にデザインを実装

一例として以下のように実装できます。
自分に好みにしていきましょう。

tweets.scss
// 新規投稿ページ
// https://www.will3in.co.jp/frontend-blog/article/5star-rating-on-contact-form7
.star-field{
    display: flex;
    flex-direction: row-reverse;
    justify-content: right;
}
.star-field input[type='radio']{
    display: none;
}
.star-field label{
    font-size: 50px;
    padding-right: 10px;
    color: #ccc;
    font-size: 30px;
    cursor: pointer;
} 
.star-field label:hover,
.star-field label:hover ~ label,
.star-field input[type='radio']:checked ~ label{
    color: rgb(255, 145, 0);
}

// 一覧表示ページ
.star{
  font-size: 50px;
  color: rgb(255, 145, 0);
}
5
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
5
0