Ruby on Rails显示半个星级的小数等级,例如4.5

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

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:

 
Star rating:

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

 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 

您可以尝试这样的事情:

 module ApplicationHelper def render_stars(value) i_value = value.floor f_value = value - i_value output = '*' * i_value output << image_tag('half_star.jpg') if f_value > 0 output end end 

您可能必须在视图中使用.html_safe

但是,您的html.erb代码段看起来不对。 它将无法正确呈现,如果您不在文件的某处关闭第一个,则会引发错误。 你想达到什么目的?