Ruby on Rails display half a star for a decimal ra

2020-02-06 18:08发布

问题:

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:

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:

<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> 

回答1:

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


回答2:

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?