How to format values ​​before saving database in rails 3

I have a User model with a Profit field. Profit field - type DECIMAL (11.0). I have a hidden input in a form that allows the user to enter something like $ 1,000. I want to format this value and delete everything except numbers from it, so I will save 1000. Here is what I still have:

class User < ActiveRecord::Base
  before_save :format_values

  private

  def format_values
    self.profit.to_s.delete!('^0-9') unless self.profit.nil?
  end
end

But it stores the value 0 in the database. It looks like it will convert it to a decimal value before my formatting function.

+5
source share
6 answers

Try the following:

def profit=(new_profit)
  self[:profit] = new_profit.gsub(/[^0-9]/, '')
end
+7
source

First of all, it is:

def format_values
  self.profit.to_s.delete!('^0-9') unless self.profit.nil?
end

about the same:

def format_values
    return if(self.profit.nil?)
    p = self.profit
    s = p.to_s
    s.delete!('^0-9')
end

, format_values - self.profit.

, , format_values, self.profit, , , , '$1,000' .

, ActiveRecord . , '$1,000' ? , . , :

> a = M.find(id)
> puts a.some_number
11
> a.some_number = 'pancakes'
 => "pancakes"
> puts a.some_number
0
> a.some_number = '$1,000'
 => "1,000"
> puts a.some_number
0
> a.some_number = '1000'
 => "1000"
> puts a.some_number
1000

, , , , AR , '$1,000' 0, . , - , , mangling, , . , - :

def some_controller
    fix_numbers_in(:profit)
    # assign from params as usual...
end

private

def fix_numbers_in(*which)
    which.select { |p| params.has_key?(p) }.each do |p|
        params[p] = params[p].gsub(/\D/, '') # Or whatever works for you
    end
end

, ActiveRecord .

, profit= , .

+6
  def format_values
    self.profit.to_d!
  end
0

@profit:

class User
  attr_accessor :profit

  def profit= value    
    @profit = value.gsub(/\D/,'')
  end
end

u = User.new
u.profit = "$1,000"
p u.profit # => "1000"
0

I would suggest using the rails number header with precision. Below is the code.

General example:

number_with_precision(111.2345, :precision => 1, :significant => true)     # => 100

Rails Code Example:

def profit=(new_profit)
  number_with_precision(self[:profit], :precision => 1, :significant => true)
end
0
source
class User < ActiveRecord::Base
  before_save :format_values

  private

  def format_values
    self.profit = profit.to_s.gsub(/\D/,'') if profit
  end
end
0
source

All Articles