计算时仅在某些时候出错:"Undefined method '/' for nil:NilClass"

Getting error only some of the time when calculating: "Undefined method '/' for nil:NilClass"

我在 Rails 上使用 Ruby 并遍历一个对象。

我想显示将两列的值相除然后乘以 100 的百分比。

不知道是直接写在view里面还是需要在model或者controller里面写方法。我首先选择将它写在视图中,但仅在某些时候出现 "Undefined method "/" for nil:NilClass" 错误。

我认为这是当其中一列没有值时抛出的错误。当我在模型或控制器中编写方法时,没有错误,但我试图显示的值是空白。

这是我的计算在视图中的样子:

show.html.erb

<%= number_to_percentage(object.column1 / object.column2.round(2) * 100, precision: 0) %>

/ 与 Ruby 中的任何其他方法一样,a / b 只是 a./(b) 的另一种说法,因此错误告诉您 object.column1nil.

你必须决定你想要object.column1.nil的意思:

  • 你们是专门展示这种东西的吗?如果是那么:

    <% if object.column1.nil? %>
      nil or whatever else you want to say
    <% else %>
      <%= object.column1 / object.column2.round(2) * 100, precision: 0) %>
    <% end %>
    
  • 你想把 nil 当作零吗?如果是那么:

    <%= object.column1.to_i / object.column2.round(2) * 100, precision: 0) %>
    

    如果 column1 是浮点值,您会希望使用 to_f 而不是 to_i。如果 n 是一个整数,那么 n.to_i == nnil.to_i == 0 所以 to_i 是隐藏常见 "treat nil as 0" 逻辑的便捷方式;同样适用于 floating_point_value.to_fnil.to_f.

如果 object.column2 也可以是 nil 那么你必须对如何处理 object.column2.nil?.

做出类似的决定