Ruby on rails 如何简化我的模型代码?

Ruby on rails 如何简化我的模型代码?,ruby-on-rails,ruby,model,Ruby On Rails,Ruby,Model,我是Rails新手,我想知道是否有任何方法可以从我的模型中简化此代码: class Item < ActiveRecord::Base def subtotal if price and quantity price * quantity end end def vat_rate if price and quantity 0.19 end end def total_vat if price and

我是Rails新手,我想知道是否有任何方法可以从我的模型中简化此代码:

class Item < ActiveRecord::Base

  def subtotal
    if price and quantity
      price * quantity
    end
  end

  def vat_rate
    if price and quantity
      0.19
    end
  end

  def total_vat
    if price and quantity
      subtotal * vat_rate
    end
  end

end
class项
据我所知,*before_filter*在模型中不起作用?

我会:

class Item < ActiveRecord::Base

  VAT_RATE = 0.19

  def subtotal
    (price || 0) * (quantity || 0)
  end

  def total_vat
    subtotal * VAT_RATE
  end

end
class项
我会:

class Item < ActiveRecord::Base

  VAT_RATE = 0.19

  def subtotal
    (price || 0) * (quantity || 0)
  end

  def total_vat
    subtotal * VAT_RATE
  end

end
class项
我个人会覆盖price和quantity的getter方法,以便它们在未设置时返回零,这允许您的其他方法在未设置值时返回有效结果,而不是检查它们是否设置并返回零

此外,创建一种提供增值税税率的方法似乎有点过分,因为它应该是一个常数。如果它不是一个常数,那么它可能应该存储在数据库中,以便修改

以下是根据我的想法对您的模型进行的修改:

class Item < ActiveRecord::Base
  VAT_RATE = 0.19

  def price
    self.price || 0
  end

  def quantity
    self.quantity || 0
  end

  def subtotal
    price * quantity
  end

  def total_vat
    subtotal * VAT_RATE
  end
end
class项
我个人会覆盖price和quantity的getter方法,以便它们在未设置时返回零,这允许您的其他方法在未设置值时返回有效结果,而不是检查它们是否设置并返回零

此外,创建一种提供增值税税率的方法似乎有点过分,因为它应该是一个常数。如果它不是一个常数,那么它可能应该存储在数据库中,以便修改

以下是根据我的想法对您的模型进行的修改:

class Item < ActiveRecord::Base
  VAT_RATE = 0.19

  def price
    self.price || 0
  end

  def quantity
    self.quantity || 0
  end

  def subtotal
    price * quantity
  end

  def total_vat
    subtotal * VAT_RATE
  end
end
class项
未设置价格和数量时是否返回零?未设置价格和数量时是否返回零?