Ruby on Rails显示半个星级的小数等级,例如4.5 [英] Ruby on Rails display half a star for a decimal rating, e.g. 4.5

查看:121
本文介绍了Ruby on Rails显示半个星级的小数等级,例如4.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以查看5个星号,产品的评级为5,等级为4等等的4个星号。但我想要做的是用我所拥有的星形图像替换星号我的资产/图像/目录,如果评级为4.5,则显示半个星。有办法做到这一点吗?下面是我在application_helper.rb中的当前代码和index.html.erb中的视图。

I am able to view 5 asterisks for a rating of 5 for a product, and 4 asterisks for a rating of 4 etc. But what I would like to do is replace the asterisks with an image of a star that I have in my assets/images/ directory, and if a rating is of 4.5 then display half a star. Is there a way of doing this? Below is my current code in application_helper.rb and the view in index.html.erb.

application_helper.rb:

application_helper.rb:

module ApplicationHelper
   def render_stars(value)
      output = ''
      if (1..5).include?(value.to_i)
         value.to_i.times { output += '*'}
      end
      output
   end
end

index.html.erb:

index.html.erb:

<div id="star-rating">
    <% if not product.no_of_stars.blank? %>
        <div id="star-rating">
    <% if product.no_of_stars.blank? %>
       <%= link_to 'Please add a Review',{ controller: 'reviews', action: 'new', id: product.id } %>
     <% else %>
        Star rating: <%= render_stars(product.no_of_stars) %>
    <% end %>
 </div> 


推荐答案

我们假设您要使用 star.gif 作为星形图像, half-star.gif 作为1/2星形图像:

Let's assume you want to use star.gif as a star image and half-star.gif as the 1/2 star image:

module ApplicationHelper
  def render_stars(value)
    output = ''
    if (1..5).include?(value.floor)
      value.floor.times { output += image_tag('star.gif')}
    end
    if value == (value.floor + 0.5) && value.to_i != 5
      output += image_tag('half-star.gif')
    end
    output.html_safe
  end
end

这篇关于Ruby on Rails显示半个星级的小数等级,例如4.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆