2017-04-05 94 views
1

在我的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 

任何想法,以更好的方式來實現這一點?

+2

爲什麼不把它們作爲整數存儲在0..100的範圍內,而是將'final_price'改爲'price *(1- discount/100.0)'? – tadman

+0

「他們最終使用0-100的值而不是0-1」 - 因爲你告訴它,在吸氣劑!爲什麼不去除重寫的吸氣劑並看看?或者,更好的做法是直接在'final_price'中使用'read_attribute(:discount)'?或者,甚至更好的是,你的0-100 getter/setter和0-1列(discount_percentage和discount_fraction,或其他)有不同的名稱,這樣你就可以按需使用。 –

+0

@tadman「爲什麼不把它們作爲整數存儲在0..100範圍內」 - 給出的理由是「使計算更簡單」。事實上,我可以看到它如何使某些報告更簡單一些。 '選擇價格*折扣AS adjusted_price ...'。 –

回答

0

我會使用一個十進制列(以避免issues with floats and rounding)來存儲原始值(以百分比形式)並避免投射。

然後,您可以簡單地通過計算淨價格:

def final_price 
    price * (discount || 100 * 0.01) 
end 

當談到與呈現輸出到你的方式想看看money gem,因爲它可以更容易地處理用戶區域設置和多種貨幣。

+0

0-100從0-1變爲簡單的「x * 0.01」 - 我無法真正看到將轉換後的值存儲在db中的值,因爲其計算起來並不複雜或昂貴。 – max