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.
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.
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%".
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%".
You can use .round
for this
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.