LoginSignup
5
2

More than 3 years have passed since last update.

【Rails】星★を用いた評価機能の実装

Last updated at Posted at 2021-01-28

はじめに

Railsを用いたオリジナルアプリケーションを開発していた時の事。
投稿する際に、星を用いた評価機能があるとかっこいいと思いトライしてみたのですが
とても苦戦したので、振り返ることができるよう書き留めておきます。

実現したい事

  • 投稿ページで★を用いた評価をする。
    raty_post.gif

  • 一覧表示ページで、投稿時に設定された★の数を表示。
    rate_view.png

postsテーブルの作成

postsテーブルにrateカラムを作成します。
今回、1.53.5 のように、0.5刻みで評価値を設定したいので、カラムの型はfloat型とします。

jQueryの導入

まずはGemfileに以下の記述を加え、忘れずにbundle installします。

Gemfile
gem 'jquery-rails'

次にapplication.jsに次のコードを追記します。

application.js
window.jQuery = window.$ = require('jquery')

この時package.jsonの編集も必要らしいのですが、ターミナルで次のコマンドを実行すればオッケーらしいです。

yarn add jquery

(jQueryの導入に関してはyarn add jqueryコマンドが何をしてくれているのかあまり分かっていないので、分かる人からしたら効率の悪い導入方法だと思われてしまうかもしれません。)

jsコードと画像の読み込み

jsコード

下記のGitHubからコードをコピーして、jquery_raty.jsなどと適当に名前をつけてapplication.jsの近くに配置します。

次にapplication.jsからrequireします。

application.js
window.jQuery = window.$ = require('jquery')

require("../jquery_raty") //追加

requireする際のjquery_raty.jsのパスはファイルの配置位置によって人それぞれなので注意です。

画像

下記のGitHubから画像を持ってきます。
star-half.pngstar-off.pngstar-on.pngの3つの画像をapp/assets/images配下に保存します。

星を用いた評価の入力と保存

new.html.erb
 <div class="" id="star">
   <%= f.label :rate,'評価 :', class:"" %>
   <%= f.hidden_field :rate, id: :review_star %>
 </div>

 <script>
 $('#star').raty({
   size     : 36,
   starOff:  '<%= asset_path('star-off.png') %>',
   starOn : '<%= asset_path('star-on.png') %>',
   starHalf: '<%= asset_path('star-half.png') %>',
   scoreName: 'post[rate]',
   half: true,
 });
 </script>

大きさの調整はclass=""で任意に設定してください。
また、下記1行目でPostモデルのrateカラムに値を保存。2行目の記述で0.5刻みの星による評価を許容しています。

scoreName: 'post[rate]'
half: true,

評価の表示

index.html.erb
 <div class="">
   <div id="star-rate-<%= post.id %>"></div>
   <script>
   $('#star-rate-<%= post.id %>').raty({
     size: 36,
     starOff:  '<%= asset_path('star-off.png') %>',
     starOn : '<%= asset_path('star-on.png') %>',
     starHalf: '<%= asset_path('star-half.png') %>',
     half: true,
     readOnly: true,
     score: <%= post.rate %>,
   });
   </script>
 </div>
 <div class="">
   <%= post.rate %>
 </div>

省略していますが、postに情報を入れてeachで回しています。
classはお好みで設定してみてください。

まとめ

星★を用いた評価機能を実装するだけで、見た目がガラッと変わり感動しました。
苦戦はしましたが、他にも実装したい機能あればどんどん挑戦していきたいです。

参考

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