繁体   English   中英

Rails4:如何显示5星图像

[英]Rails4: How to display 5 star images

我能够看到5颗星的文章评分为5,而4颗星的评分为4, 依此类推 。我引用Ruby on Rails将半颗星显示为十进制,例如4.5

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

尽管我知道一些像ratratrate这样的宝石,但我想知道如何不使用宝石来描述。

\\程序\\佣工\\ 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 %>
...

我对您的代码做了一些修改,以尝试处理所有情况。 看评论。

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

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

附加字符串时,我还会使用<<而不是+= -更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM