Rails 在编辑表单上转换百分比值 [英] Rails Convert Percentage Value on Edit Form
问题描述
我的 Customer
模型中有以下回调和方法.
I have the following callback and method in my Customer
model.
before_save :convert_commission_percentage
def convert_commission_percentage
self.commission= commission.to_f/100.to_f
end
这允许用户输入百分比为 45
并将其存储为 .45
.但是,在编辑时,此百分比的字段在编辑表单上显示为 .45
,导致该数字在更新时再次除以 100.有没有办法通过将编辑字段显示为 45
来防止这种情况发生?
This allows the user to input a percentage as 45
and store it as .45
. However, on edit, the field for this percentage is then displayed as .45
on the edit form, causing that number to be divided by 100 again on update. Is there a way to keep this from happening by displaying the edit field as 45
?
推荐答案
有几个选项:
为什么存储转换后的值,为什么不存储用户输入的任何内容而不做修改.
commission_percentage
可能是一个更好的名字.如果您想使用commission
,您可以使用alias_attribute :commission, :commission_percentage
创建一个别名commission
到commission_percentage
> 属性而不是应用程序中的commission_percentage
属性.
Why store converted value, why not store whatever the user inputs without modification.
commission_percentage
might be a better name. You could create an aliascommission
tocommission_percentage
withalias_attribute :commission, :commission_percentage
if you'd like to usecommission
attribute instead ofcommission_percentage
attribute in your application.
使用 after_initialize
回调:
before_save :convert_commission_percentage
after_initialize do
commission = commission.to_f * 100
end
def convert_commission_percentage
self.commission= commission.to_f/100.to_f
end
通过 getter 和 setter:
Through getters and setters:
def commission=(value)
write_attribute :commission, value.to_f/100
end
def commision
read_attribute(:commission).to_f * 100
end
这篇关于Rails 在编辑表单上转换百分比值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!