NoMethodError - Rails模型中的计算

时间:2016-11-11 14:37:49

标签: ruby-on-rails model-view-controller

我有一个项目模型。在该模型中,我需要能够计算产品的利润。但是,如果我刚购买该商品,则显然尚未购买,sold_forfeesshipping的值将为空。如果没有输入值,我会得到undefined method - '为nil:NilClass error. I tried救援NoMethodError`,但之后它不会计算利润。有没有办法避免错误并让我的计算工作?

items.rb

class Item < ActiveRecord::Base
  def profit_calc
    sold_for - bought_for - fees - shipping
  end

  def self.purchase_total
    sum(:bought_for)
  end

  def self.fee_total
    sum(:fees)
  end

  def self.shipping_total
    sum(:shipping)
  end

  def self.sales_total
    sum(:sold_for)
  end

  def self.profit_total
    sum(:sold_for) - sum(:bought_for) - sum(:fees) - sum(:shipping)
  end

  scope :visible, -> { where(sold: false) }
  scope :sold, -> { where(sold: true) }
end

html.erb:

<td><%= number_to_currency(item.profit_calc) %></td>

2 个答案:

答案 0 :(得分:2)

如果出现任何错误或发生任何类型的错误,profit_calc应返回0,那么您可以尝试:

def profit_calc
  sold_for - bought_for - fees - shipping rescue 0
end

答案 1 :(得分:0)

你可以尝试

def profit_calc
    if sold_for then return (sold_for - bought_for - fees - shipping) else return 0 end 
  end