[英]How can I add data-massaging code to a model attribute?
I'm working with a legacy database where a certain percentage value is stored in a DECIMAL
column, but users enter and read the data as whole numbers. 我正在使用遗留数据库,其中某个百分比值存储在
DECIMAL
列中,但用户输入并读取整数数据。
So, let's say the DB includes... 所以,让我们说数据库包含......
contracts
---------
funded_percent DECIMAL 10,5
I'd like to add a "getter" and "setter" to the ActiveRecord model for that table multiply by 100 on read and divide by 100 on save. 我想在该表的ActiveRecord模型中添加一个“getter”和“setter”,在读取时乘以100并在保存时除以100。
The motivation is so that in my view code, I'm only dealing with whole numbers. 动机是这样的,在我的视图代码中,我只处理整数。
I'm not sure of the correct way to do that. 我不确定这样做的正确方法。
Oh, and some of the values go past three decimal places. 哦,有些值超过了小数点后三位。
So the method would need to round a stored value of "0.036" to a displayed value of "4%". 因此,该方法需要将存储的值“0.036”舍入到显示值“4%”。
here you refer to the attribute as "funded" to deal in whole numbers 在这里,您将属性称为“已资助”以处理整数
def funded=(other)
self.funded_percent = other / 100
end
def funded
funded_percent * 100
end
"0.036" to a displayed value of "4%".
“0.036”到显示值“4%”。
You can use .round
for this 你可以使用
.round
def funded
( funded_percent * 100 ).round
end
Please try the following: 请尝试以下方法:
def funded_percent=(value)
write_attribute :funded_percent, value/100 if value.present?
end
def funded_percent
(read_attribute :funded_percent) * 100
end
Then in your view you could use funded_percent.ceil
然后在您的视图中,您可以使用
funded_percent.ceil
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.