Rails / ActiveRecord: field normalization

I am trying to remove commas from a field in a model. I want the user to dial a number, i.e. 10,000, and this number should be stored in the database as 10,000. I was hoping I could do some normalization on the model side to remove the comma. I don’t want to depend on the view or controller to properly format my data.

I tried:

before_validation :normalize

def normalize 
 self['thenumber'] = self['thenumber'].to_s.gsub(',','')
end

no performance.

+3
source share
5 answers

The problem with this is that for some time non-standardized material will exist in the object; if you have code that works with attributes before the material normalizes, then this will be a problem.

:

def thenumber=(value)
  # normalise stuff here, call write_attribute
end

, , Rails- , , .

, .

+1

http://github.com/mdeering/attribute_normalizer . :

  # By default it will strip leading and trailing whitespace
  # and set to nil if blank.
  normalize_attributes :author, :publisher

  # Using one of our predefined normalizers.
  normalize_attribute  :price, :with => :currency

  # You can also define your normalization block inline.
  normalize_attribute :title do |value|
    value.is_a?(String) ? value.titleize.strip : value
  end

, - :

  normalize_attribute :title do |value|
    value.to_s.gsub(',', '')
  end
+7

, . :

test "should remove commas from thenumber" do
  f = Foo.new(:thenumber => "10,000")
  f.save
  f = Foo.find(f.id)
  assert f.thenumber == "10000"    
end

.

 class Foo < ActiveRecord::Base
  before_validation :normalize

  def normalize 
    self['thenumber'] = self['thenumber'].to_s.gsub(',','')
  end

 end

, thenumber , .

Started
.
Finished in 0.049666 seconds.

1 tests, 1 assertions, 0 failures, 0 errors

db , :

 def thenumber=(value)
   self['thenumber'] = value.to_s.gsub(',','').to_i
 end

-, , AR....

>> f.thenumber = "10,000"
=> "10,000"
>> f.thenumber
=> 10

Ruby ... , , .

irb(main):004:0> i = "155-brian-hogan".to_i
=> 155

,

/users/155-brian-hogan

@user = User.find_by_id(params[:id])

, .

, col , setter:)

!

+4

ruby ​​ a. ['']? , , , .

self.thenumber = self.thenumber.to_s.gsub(',','')
0

true before_validation, , , self ['thenumber'], false, Rails:

before_ * false, .

, , Rails, , nil/false/blank .

before_validation :normalize

def normalize 
  self['thenumber'] = self['thenumber'].to_s.gsub(',','')
  return true
end
0

Source: https://habr.com/ru/post/1708671/


All Articles