How can I only display a certain div if a record exists?
I have venue records where each has reviews, each review can be rated 1 to 5 and I'm displaying the average review rating using:
<%= @venue.reviews.average(:rating) %>
I'd like to represent the rating as star images instead of a number.
I have this setup in my view to hold the stars:
<div class="star_rating_container">
<div class="star_rating" style="width: <%= @venue.reviews.average(:rating)*20 %>px;">
</div>
</div>
with this css:
.star_rating_container {
width: 100px;
height: 20px;
background-image: url(/images/dim_star.png);
}
.star_rating {
height: 20px;开发者_StackOverflow社区
background-image: url(/images/lit_star.png);
}
The problem however is that I get a "You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.*" error when I try to view a venue which has no reviews.
I'm super new to programming and am struggling with how to fix this.
Thanks for any help its much appreciated!
You want to do:
<%= (@venue.reviews.average(:rating) || 0 ) *20 %>
This way, if you have no ratings, it will default to 0, thus not throwing an error but also providing the desired results of setting the width to 0. If you do have reviews, it will short circuit to the average rating for that venue.
The problem here was that .average() was returning nil when there wasn't any reviews, so it was doing (nil * 20)... which obviously doesn't work.
You can get tricky, the but most straightforward solution is this:
<% unless @venue.reviews.empty? %>
<div class="star_rating_container">
<div class="star_rating" style="width: <%= @venue.reviews.average(:rating)*20 %>px;">
</div>
</div>
<% end %>
Change it to <%= @venue.reviews.average(:rating)*20 rescue 0 %>
. This way you'll have 0 width style
精彩评论