LoginSignup
9
21

More than 3 years have passed since last update.

【Rails】raty.jsを使った評価機能を作る

Last updated at Posted at 2021-01-18

raty.jsを使って、railsアプリに星画像付きの評価機能を実装する方法です。jqueryが必要です。

 2021-01-18 21.35.22.png

環境

$ rails -v
Rails 5.2.4.4

jqueryを導入

Gemfile
gem 'jquery-rails'
$ bundle install
app/assets/javascripts/application.js
//= require jquery

jquery.raty.jsを作成

$ touch app/assets/javascripts/jquery.raty.js

作成したファイルに、https://github.com/wbotelhos/raty/blob/master/lib/jquery.raty.js 内の記述をコピペ。その後application.jsでrequire(jqueryより後に書く)

app/assets/javascripts/application.js
//= require jquery.raty.js

星の画像を配置

https://github.com/wbotelhos/raty/tree/master/lib/images からstar-on.pngstar-off.pngstar-half.pngをダウンロードして、app/assets/images以下に配置。

評価を保存するカラムを持つデータを作成

$ rails g migration addEvaluationToMovie evaluation:float
db/migrate/202101011111.rb
class AddEvaluationToMovie < ActiveRecord::Migration[5.2]
  def change
    add_column :movies, :evaluation, :float
  end
end
$ rails db:migrate

評価投稿画面を作成

今回は例として、お気に入りの映画のタイトルを投稿する画面で、評価も一緒に投稿できるようにしてみます。

app/views/movies/new.html.erb
<h2>お気に入りの映画を投稿</h2>
<%= form_with(model: movie, local: true) do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div id="evaluate_stars">
    <label>評価</label>
  </div>
  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
<script>
  $('#evaluate_stars').raty({
    starOn: "<%= asset_path('star-on.png') %>",
    starOff: "<%= asset_path('star-off.png') %>",
    starHalf: "<%= asset_path('star-half.png') %>",
    scoreName: 'movie[evaluation]' //登録するモデル名とカラム名を記述
  });
</script>
app/controllers/movies_controller.rb
def movie_params
  params.require(:movie).permit(:title, :evaluation) # evaluationを追加
end

投稿した評価を表示

ここでは例としてindexページに評価を表示します。

app/views/movies/index.html.erb
<h1>映画一覧</h1>
<table>
  <thead>
    <tr>
      <th>タイトル</th>
      <th>評価</th>
    </tr>
  </thead>
  <tbody>
    <% @movies.each do |movie| %>
      <tr>
        <td><%= movie.title %></td>
        <td class="movie-evaluation" data-score="<%= movie.evaluation %>"></td>
      </tr>
    <% end %>
  </tbody>
</table>
<script>
  $('.movie-evaluation').raty({
    readOnly: true,
    score: function() {
      return $(this).attr('data-score');
    },
    path: '/assets/'
  });
</script>

参考

9
21
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
9
21