Describes how to display the average value of each store's evaluation on the list display page! The image looks like this.
This implementation is
Farstep [Programming Course]
[[Ruby on Rails] Let's create a star review function (PART1) How To Create a Star Rating with Ruby on Rails](https://www.youtube.com/watch? v = NOOYABsAip0) is used as a reference.
ruby 2.6.5 Ruby on Rails 6.0.3.3 I am using Bootstrap 4 with some margins specified.
model
class Laundry < ApplicationRecord
def avg_score
unless self.comments.empty?
comments.average(:rate_id).round(1)
else
0.0
end
end
def avg_score_percentage
unless self.comments.empty?
comments.average(:rate_id).round(1).to_f*100/5
else
0.0
end
end
end
First, the average value is calculated if the comment exists according to whether it is empty or not. Use the average method to get the average value of the column names. Round (1) `` to round off to the second decimal place.
The avg_score_percentage
method calculates the percentage and passes it to the view.
The code is below.
html
<div class="average-score mb-3">
<div class="star-rating ml-2">
<div class="star-rating-front" style="width: <%= laundry.avg_score_percentage %>%">★★★★★</div>
<div class="star-rating-back">★★★★★</div>
</div>
<div class="average-score-display">
(<%= laundry.avg_score %>point)
</div>
</div>
css
.average-score {
display: flex; //★ and points side by side
justify-content: center;
}
.star-rating {
position: relative;
width: 5em;
height: 1em;
font-size: 17px;
}
.star-rating-front {
position: absolute;
top: 0;
left: 0;
overflow: hidden; //Hide the part that extends beyond the specified width.
white-space: nowrap; //Avoid wrapping when the width is not enough.
color: #ffcc33;
height: 25px;
}
.star-rating-back {
color: #ccc;
}
We will implement by preparing two 5 stars (★★★★★) and superimposing the two.
・ .Star-rating-front
・ ・ ・ Specify the width by overlaying the yellow star part on top of it with "width: <% = laundry.avg_score_percentage%>%
.
・ .Star-rating-back
・ ・ ・ The gray star part, the part that did not turn yellow by placing it below is filled.
I think the following two points are the points.
Specify overflow: hidden;
.
By specifying overflow: hidden;
, the part outside the specified width is hidden and the gray star behind is displayed.
If you do not specify this, even if you specify the width, the part that extends beyond the width is not hidden, so it will always be evaluated as 5 stars.
overflow: hidden;
none
By setting white-space: nowrap;
, it will not wrap when the width is not enough.
By specifying this, the score after the decimal point will also be reflected in the star.
white-space: nowrap;
Yes
white-space: nowrap;
none
You can now display the average rating as a star!
Recommended Posts