简体   繁体   English

保存Rails 4之前编辑值

[英]Edit value before saving Rails 4

In my view file I have code like this 在我的查看文件中,我有这样的代码

<%= f.text_field :family_allowance, :value => number_to_currency(10000, :format => "%u%n", :unit => "¥", precision: 0), class: "form-control", :readonly => true %>

I want to convert the string value to integer before I save to db. 我想在保存到数据库之前将字符串值转换为整数。 In my model I tried 在我的模型中,我尝试

before_save :set_allowance_value
.
.
.
private 
  def set_allowance_value
    this.family_allowance = (this.family_allowance.sub ",", "").to_i
    true
  end

This doesn't work, what is the best way to do this ? 这行不通,什么是最好的方法?

Adding this to your model should work. 将此添加到您的模型应该可以。

def family_allowance=(allowance)
  self[:family_allowance] = allowance.delete(',').to_i # it'll work if allowance is like "1,32,200" 
  # you can also use sub/gsub/tr option 
end

You can use write_attribute to write directly to the attribute when changing its value through a setter; 通过设置器更改属性值时,可以使用write_attribute直接写入属性。

def family_allowance=(allowance)
    write_attribute :family_allowance, allowance.gsub(",", "").to_i
end

Since you are creating a setter, there is no more need to run your code in a before_save callback. 由于您正在创建设置器,因此不再需要在before_save回调中运行代码。

Also, you can use the value in validations etc... 另外,您可以在验证等中使用该值...

However, be carefull when automatically assuming the allowance is a string. 但是,当自动假定allowance为字符串时,请小心。 Maybe you want to test to see if it responds to gsub first; 也许您想测试一下它是否首先响应gsub;

def family_allowance=(allowance)
    if allowance.respond_to?(:gsub)
      write_attribute :family_allowance, allowance.gsub(",", "").to_i
    end
end

def set_allowance_value def set_allowance_value

fa = self.family_allowance.split('').map {|x| fa = self.family_allowance.split('')。map {| x | Integer(x) rescue nil }.compact.join.to_i 整数(x)抢救nil} .compact.join.to_i

# if Your family_allowance value is consisting of "¥10,000" #如果您的family_allowance值包含“¥10,000”


self.family_allowance = fa self.family_allowance = fa

end 结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM