Ruby/Rails - Is it possible to perform ruby calculations in the view?
I'm trying to perform a calculation that looks to me like it has to be in the view so far.
In the view I have
<% for post in @user.posts %>
<%= post.tasks.count / @projects.tasks.count %>
<% end %>
I'm trying to display the a percentage.... When I place <%= post.tasks.count %> by itself it displays 2 and <%= @projects.tasks.count %> it displays 4.
But when I try to do <%= post.tasks.count / @projects.tasks.count %> it displays 0 not .50 or 1/2.
The reason I'm performing this logic in the view an开发者_运维技巧d not the controller is that I would like to display the dynamic percentage for each iteration of the for loop
The reason you're getting zero is that both numbers are integers, so it's doing integer division. If you convert the first to a float, then you'll get a float as the result.
If you want to format the number as a percentage, you'll also want to use the number_to_percentage
helper as well. So your view code would look something like this:
<%= number_to_percentage( post.tasks.count.to_f / @projects.tasks.count ) %>
And would produce the output 50%
in your view. You can also specify the precision and some formatting options to that helper, if you need to customize it further.
Integer arithmetic produces integer results. Try:
<%= post.tasks.count.to_f / @projects.tasks.count %>
To get control of display precision and the like you might want something like:
<%= "%4.2f" % (post.tasks.count.to_f / @projects.tasks.count) %>
精彩评论