【问题标题】:I need to calculate a percentage in a partial, then put it into a progress bar (Bootstrap)我需要计算部分百分比,然后将其放入进度条(Bootstrap)
【发布时间】:2015-10-12 23:53:31
【问题描述】:

我正在尝试计算单个目标缩略图的百分比,然后在 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。

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

【问题讨论】:

  • 这可能只是我一个格式化的东西,但它应该是“宽度:”在这个例子中你只有“宽度”。

标签: ruby-on-rails twitter-bootstrap


【解决方案1】:

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

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

【讨论】:

  • 我做了什么:@percentage = @user.books.count.to_f/goal.amount.to_f
猜你喜欢
  • 2014-08-14
  • 2010-11-22
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 2023-02-08
相关资源
最近更新 更多