It is a method to implement the evaluation function with a star image in the rails application using raty.js. You need jquery.
$ rails -v
Rails 5.2.4.4
Gemfile
gem 'jquery-rails'
$ bundle install
app/assets/javascripts/application.js
//= require jquery
$ touch app/assets/javascripts/jquery.raty.js
Copy and paste the description in https://github.com/wbotelhos/raty/blob/master/lib/jquery.raty.js to the created file. Then require in application.js
(write after jquery)
app/assets/javascripts/application.js
//= require jquery.raty.js
Download star-on.png
, star-off.png
, star-half.png
from https://github.com/wbotelhos/raty/tree/master/lib/images and app Placed under/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
This time, as an example, let's make it possible to post the evaluation together on the screen for posting the title of your favorite movie.
erb:app/views/movies/new.html.erb
<h2>Post your favorite movie</h2>
<%= form_with(model: movie, local: true) do |form| %>
<div>
<%= form.label :title %>
<%= form.text_field :title %>
</div>
<div id="evaluate_stars">
<label>Evaluation</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]' //Describe the model name and column name to be registered
});
</script>
app/controllers/movies_controller.rb
def movie_params
params.require(:movie).permit(:title, :evaluation) #Added evaluation
end
Here, as an example, the evaluation is displayed on the index page.
erb:app/views/movies/index.html.erb
<h1>Movie list</h1>
<table>
<thead>
<tr>
<th>title</th>
<th>Evaluation</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>
Recommended Posts