如何简化我的模型代码?
我是新来的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
据我所知* *的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
谢谢,作品像魅力! – Tintin81 2012-03-08 12:17:16
个人,让他们返回零没有设置时,允许在没有值设置你的其他方法,以返回有效结果我将会覆盖价格和数量的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
+1获取者覆盖 – apneadiving 2012-03-08 12:06:20
工作得很好,非常感谢。 – Tintin81 2012-03-08 12:17:35
返回零时的价格和数量都没有设置? – apneadiving 2012-03-08 11:55:46