Tony Vincent
Tony Vincent

Reputation: 14262

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 ?

Upvotes: 1

Views: 246

Answers (3)

sai sagar
sai sagar

Reputation: 1

def set_allowance_value

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

# if Your family_allowance value is consisting of "¥10,000"


self.family_allowance = fa

end

Upvotes: 0

Stijnster
Stijnster

Reputation: 209

You can use write_attribute to write directly to the attribute when changing its value through a setter;

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.

Also, you can use the value in validations etc...

However, be carefull when automatically assuming the allowance is a string. Maybe you want to test to see if it responds to gsub first;

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

Upvotes: 1

Emu
Emu

Reputation: 5895

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

Upvotes: 1

Related Questions