如果有记录,如何只显示某个div?
我有场地记录,其中每个评论都有评论,每个评论可以评级为 1 到 5,并且我使用以下方式显示平均评论评级:
<%= @venue.reviews.average(:rating) %>
我想将评级表示为星级图像而不是数字。
在我看来,我有这样的设置来容纳星星:
<div class="star_rating_container">
<div class="star_rating" style="width: <%= @venue.reviews.average(:rating)*20 %>px;">
</div>
</div>
使用这个 css:
.star_rating_container {
width: 100px;
height: 20px;
background-image: url(/images/dim_star.png);
}
.star_rating {
height: 20px;
background-image: url(/images/lit_star.png);
}
但是问题是我得到一个“当你没有预料到它时你有一个 nil 对象!你可能期望一个 Array 的实例。发生了错误当我尝试查看没有评论的场所时,评估 nil.*” 错误。
我对编程非常陌生,并且正在努力解决如何解决这个问题。
感谢您的帮助,非常感谢!
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;
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你想要这样做:
这样,如果你没有评分,它将默认为 0,因此不会抛出错误,但也提供将宽度设置为 0 的所需结果。如果你确实有评论,它将短路到该场地的平均评分。
这里的问题是 .average() 在没有任何评论时返回 nil,所以它正在执行 (nil * 20)...这显然不起作用。
You want to do:
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:
将其更改为
<%= @venue.reviews.average(: rating)*20rescue 0 %>
。这样你就会有 0 宽度样式Change it to
<%= @venue.reviews.average(:rating)*20 rescue 0 %>
. This way you'll have 0 width style