Reputation: 149
I'm currently trying to implement a simple star review system to my application and I got it working for the most part. But the issue Is I can't get the the review stars to show for the average review of a store. Anyone mind helping me understand what is broken?
stores/show.html.erb:
<div class="star-rating" data-score= <%= @avg_review %> ></div>
<em><%= "#{@reviews.length} reviews" %></em>
This is included at the bottom of the view:
<script>
$('.star-rating').raty({
path: '/assets/',
readOnly: true,
score: function() {
return $(this).attr('data-score');
}
});
</script>
stores_controller.rb:
def show
@reviews = Review.where(store_id: @store.id).order("created_at DESC")
if @review.blank?
@avg_review = 0
else
@avg_review = @reviews.average(:rating).round(2)
end
end
Thank you a head of time.
Upvotes: 0
Views: 77
Reputation: 141
Put in your model store:
def average_rating
reviews.count == 0 ? 0 : reviews.average(:rating).round(2)
end
(If no star = 0, otherwise we average the notes)
In your view:
<span id="average_rating"></span>
With the script:
<script>
$('#average_rating').raty({
path: '/assets',
readOnly: true,
score: <%= @store.average_rating %>
});
</script>
Upvotes: 1