Ruby on Rails display half a star for a decimal rating, e.g. 4.5

依然范特西╮ 提交于 2019-11-28 13:09:17

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

You can try with something like this:

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

You might have to use .html_safe in the view.

Your html.erb snippet looks wrong, however. It won't render correctly, and it will raise an error if you don't close the first if somewhere down the file. What do you want to achieve?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!