ruby-on-rails – 如何在Rails中验证前从值中删除美元符号?
发布时间:2020-12-16 21:31:54 所属栏目:百科 来源:网络整理
导读:这是我在我的模型中使用的内容: before_validation :strip_dollar_signvalidates :amount_due,:format = { :with = /^d+??(?:.d{0,2})?$/ },:numericality = {:greater_than = 0}privatedef strip_dollar_sign self.amount_due = self.amount_due.to_s.t
这是我在我的模型中使用的内容:
before_validation :strip_dollar_sign validates :amount_due,:format => { :with => /^d+??(?:.d{0,2})?$/ },:numericality => {:greater_than => 0} private def strip_dollar_sign self.amount_due = self.amount_due.to_s.tr!('$,','').to_f end 如果我在Rails控制台中手动运行strip_dollar_sign函数中的行,我得到了我想要的(即400美元最终为400.0)但是当我在我的应用程序中使用实际表单时,值总是最终为0.0.有人抓到我做错了吗? 解决方法
这里有三个问题:
>正如Stefan在his answer中指出的那样,你可能想删除你的tr!打电话,虽然它不会影响$的更换. def amount_due=(value) value = value.to_s.tr('$','').to_f write_attribute(:amount_due,value) end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |