Rails 在编辑表单上转换百分比值 [英] Rails Convert Percentage Value on Edit Form

查看:33
本文介绍了Rails 在编辑表单上转换百分比值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

有几个选项:

  1. 为什么存储转换后的值,为什么不存储用户输入的任何内容而不做修改.commission_percentage 可能是一个更好的名字.如果您想使用 commission,您可以使用 alias_attribute :commission, :commission_percentage 创建一个别名 commissioncommission_percentage> 属性而不是应用程序中的 commission_percentage 属性.

  1. Why store converted value, why not store whatever the user inputs without modification. commission_percentage might be a better name. You could create an alias commission to commission_percentage with alias_attribute :commission, :commission_percentage if you'd like to use commission attribute instead of commission_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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆