Rails4:如何显示5星图像

时间:2015-02-13 18:50:48

标签: ruby-on-rails ruby ruby-on-rails-4

我可以查看5颗星的评级为5分,4分等级为4分等。 我引用了Ruby on Rails display half a star for a decimal rating, e.g. 4.5

如果评级不是5星,我想做的是显示“star-off.png”。 例如,如果评分为3,则显示3“star-on.png”和2“star-off.png”。

虽然我知道一些像ratyrate这样的宝石,但我想知道如何在不使用宝石的情况下进行描述。

\应用\助手\ application_helper.rb

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

\ app \ views \ articles \ _article.html.erb

...
    <% if article.rating.blank? %>
    <% else %>
      <%= render_stars(article.rating) %>
    <% end %>
...

2 个答案:

答案 0 :(得分:1)

我已经重新编写了一些代码来尝试处理所有情况。见评论。

def render_stars(value)
  output = ''

  # Saved to variable for efficiency
  floored = value.floor

  # Adding full stars: If value is 2.5 then floored 
  # will be 2 (two full stars)
  floored.times { output << image_tag('star-on.png') }

  # Getting the decimal part of the value by subtracting the
  # floored value, by the value. So if value is 2.7, then will be
  # 0.7 (Changed to >= to account for ability to use numbers like
  # 2.7 and will display a half star. If you would like to only
  # handle 0.5 then change back to ==)
  if (value - floored) >= 0.5
      output << image_tag('star-half.png')
  end

  # Completes sequence of 5 stars. Ex: if value is 2.7 then 5 - 2.7
  # is 2.3 The output will already have 2 full stars and 1 half star
  # so by flooring 2.3 we will get 2, which completes the total of 5
  #stars
  (5 - value).round.times { output << image_tag('star-off.png') }
  output.html_safe
end

答案 1 :(得分:0)

我建议将方法改为以5的循环(对于5颗星)开始,并确定循环中的每个位置是开启,半开还是关闭。

我在附加字符串时也会使用<<代替+= - 更快。