--Allows you to enter and register by star rating --Display registered star rating
Set the column to save the evaluation. The column type uses the float type to enable half-star evaluation.
db/migrate/20XXXXXXXXXXXX_create_posts.rb
class CreatePosts < ActiveRecord::Migration[6.0]
def change
create_table :posts do |t|
~Abbreviation~
t.float :evaluation, null: false
~Abbreviation~
end
end
end
https://github.com/wbotelhos/raty/tree/master/lib/images Download the star image from the link above. Place it in a folder in assets / images.
https://github.com/wbotelhos/raty/blob/master/lib/jquery.raty.js Copy the code from the link above. Paste it into assets / javascript / application.js. ** Since it is written in jquery, it is also necessary to install jquery. ** **
You can enter the star rating by writing the following in the view file.
ruby:app/views/posts/new.html.erb
<%= form_with model: @post, local: true do |f| %>
~Abbreviation~
<div class="field" id="star">
<%= f.label :evaluation, "Star rating:" %>
<%= f.hidden_field :evaluation, id: :review_star %>
<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[evaluation]', #Save to evaluation column
half: true, #Half star input
});
</script>
</div>
~Abbreviation~
<% end %>
You can display the result of star evaluation by writing the following in the view file that displays the details.
ruby:app/views/posts/show.html.erb
<% @posts.each do |post| %>
~Abbreviation~
<div class="relative-post-evaluation">
<span>Evaluation:</span>
<span id="star-rate-<%= post.id %>"></span>
<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, #Half star display
readOnly: true, #Read-only
score: <%= post.evaluation %>, #Display of star rating
});
</script>
<%= post.evaluation %>
</div>
~Abbreviation~
<% end %>
https://qiita.com/yuki_0920/items/a966d9fa2bdb621f805d https://qiita.com/kitaokeita/items/1e40724c3384507cec13 https://qiita.com/busitora2/items/5b59d1ea9e90c1b016b4
Recommended Posts