如何使用模型方法增加 Bootstrap 进度条?

How to increment Bootstrap Progressbar with Model Method?

例如,如果 "Meditate""Level 2" 上有 5 days_in_current_level 和 10 days_left_in_current_level(共 15 天)进度条如何反映蓝色跨越 33% 和灰色跨越 67% 的比例?

index.html.erb

<td class="stretch">
  <div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="10" style="width: 60%;">
        <%= challenged.days_in_current_level %>
    </div>
    <div class="days-left"> 
        <%= challenged.days_left_in_current_level %> 
    </div>
  </div>
</td>

habit.rb

def days_in_current_level
    def n_days
        ((date_started.to_date)..Date.today).count do |date|
            committed_wdays.include? date.wday
        end - self.real_missed_days
    end

    case n_days
      when 0..9
        n_days
      when 10..24
        n_days-10
      when 25..44
        n_days-25
      when 45..69
        n_days-45
      when 70..99
        n_days-70
      else
        0 # No end
    end
end

def days_left_in_current_level
    def n_days
        ((date_started.to_date)..Date.today).count do |date|
            committed_wdays.include? date.wday
        end - self.real_missed_days
    end

    case n_days
      when 0..9
        10-n_days
      when 10..24
        25-n_days
      when 25..44
        45-n_days
      when 45..69
        70-n_days
      when 70..99
        100-n_days
      else
        0 # No end
    end
end

如果您需要进一步的解释、代码或视觉效果来帮助我,请告诉我 =)

将宽度设置为:

days_in_current_level / (challenged.days_in_current_level + days_left_in_current_level ).to_f * 100

您可以通过将部分除以总数得到百分比,然后将其乘以 100 以获得所需的形式。

在这种情况下,它计算为:

5 / (5+10) * 100 = 5/15 * 100 = 33.333...

示例代码:

# In your model
def progress_in_percent
  days_in_current_level / (challenged.days_in_current_level + days_left_in_current_level ).to_f * 100
end

# In your view
<div class="progress-bar" role="progressbar" aria-valuenow="10" aria-valuemin="0" aria-valuemax="10" style="width: <%= challenged.progress_in_percent %>%;">