在我的Rails應用程序中,我希望用戶能夠將百分比值以0.0到100.0的小數形式輸入。在數據庫中,我想將它們存儲爲從0.00到1.00的小數位,以便計算更容易。在Ruby on Rails中通過getter和setter表示百分比
我目前正在通過模型中的getters和setters來完成此操作。但是,當我寫在模型派生屬性,他們最終使用0-100值,而不是0-1,這違背了將其存儲在方便的計算值0-1的目的:
# in the model `quote.rb`
def discount=(value)
write_attribute :discount, value.to_f/100
end
def discount
read_attribute(:discount).to_f * 100
end
def final_price
price * (1 - discount)
# this generates a wrong value,
# because if the user inputs discount as 50 to represent 50%,
# the final price will be `price * -49`
end
任何想法,以更好的方式來實現這一點?
爲什麼不把它們作爲整數存儲在0..100的範圍內,而是將'final_price'改爲'price *(1- discount/100.0)'? – tadman
「他們最終使用0-100的值而不是0-1」 - 因爲你告訴它,在吸氣劑!爲什麼不去除重寫的吸氣劑並看看?或者,更好的做法是直接在'final_price'中使用'read_attribute(:discount)'?或者,甚至更好的是,你的0-100 getter/setter和0-1列(discount_percentage和discount_fraction,或其他)有不同的名稱,這樣你就可以按需使用。 –
@tadman「爲什麼不把它們作爲整數存儲在0..100範圍內」 - 給出的理由是「使計算更簡單」。事實上,我可以看到它如何使某些報告更簡單一些。 '選擇價格*折扣AS adjusted_price ...'。 –