[英]How can I add data-massaging code to a model attribute?
我正在使用遺留數據庫,其中某個百分比值存儲在DECIMAL
列中,但用戶輸入並讀取整數數據。
所以,讓我們說數據庫包含......
contracts
---------
funded_percent DECIMAL 10,5
我想在該表的ActiveRecord模型中添加一個“getter”和“setter”,在讀取時乘以100並在保存時除以100。
動機是這樣的,在我的視圖代碼中,我只處理整數。
我不確定這樣做的正確方法。
哦,有些值超過了小數點后三位。
因此,該方法需要將存儲的值“0.036”舍入到顯示值“4%”。
在這里,您將屬性稱為“已資助”以處理整數
def funded=(other)
self.funded_percent = other / 100
end
def funded
funded_percent * 100
end
“0.036”到顯示值“4%”。
你可以使用.round
def funded
( funded_percent * 100 ).round
end
請嘗試以下方法:
def funded_percent=(value)
write_attribute :funded_percent, value/100 if value.present?
end
def funded_percent
(read_attribute :funded_percent) * 100
end
然后在您的視圖中,您可以使用funded_percent.ceil
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.