我需要计算部分百分比,然后将其放入进度条(Bootstrap)

时间:2015-07-22 21:36:30

标签: ruby-on-rails twitter-bootstrap

我正在尝试计算单个目标缩略图的百分比,然后在Bootstrap进度条中使用它。要计算百分比,我会找到他们已经读过的书籍数量(@ user.books.count),除以他们想要阅读的数量(goal.amount),然后乘以100得到百分比。这是我到目前为止所做的:

show.html.erb

<% provide(:title, "Your goals") %>
<div class="row">
  <div class="col-md-7">
    <h2 class = "top-5-margins">Your Goals</h2>
  </div>

  <div class="col-md-5">
    <%= link_to "New goal", add_goal_path, class: "btn btn-lg btn-default green-hover" %>
  </div>
</div>
<% if @user.goals.any? %>
    <div class="row">
            <%= render @user.goals %>
    </div>
<% else %>
    <p class = "center">You don't have any goals set. You should make one now.</p>
<% end %>

_goal.html.erb:

<div class="col-sm-6 col-md-4">
  <div class="thumbnail">
    <div class="caption">
        <h3 class = "center"><%= goal.title %></h3>
        <div class="progress">
            <% @percentage = @user.books.count/goal.amount * 100 %>
            <% puts @percentage %>
            <div class="progress-bar" role="progressbar" aria-valuenow=<%=@percentage.to_s%> aria-valuemin="0" aria-valuemax="100" style=<%= "width" + @percentage.to_s + "%;"%>><%= @percentage.to_s %>
        </div>
    </div>
    <h3><%= @user.books.count %> out of <%= goal.amount %></h3></span>
    <h4>Created on: <%= goal.created_at.strftime("%m/%d/%Y") %></h4>
  </div>
</div>

但是当我查看页面时,进度条没有任何进展,@ percentage的值似乎为0.

An individual goal

*我知道你应该将你的计算和变量放在控制器中(将@percentage的赋值放在控制器中)但是我不知道如何让它工作。

1 个答案:

答案 0 :(得分:1)

当你调用@ user.books.count时,它返回一个整数。您需要将其转换为浮点数。或者你可以将目标金额保存为浮动。

>> count = 5
=> 5 
>> goal = 10
=> 10
>> count/goal
=> 0