Unable to understand the reasons for activerecord rails

believe that I have a transition as follows

create_table :dummies do |t|
  t.decimal :the_dummy_number
end 

i is created as follows

dummy = Dummy.new
dummy.the_dummy_number = "a string"
puts dummy.the_dummy_number

conclusion for the above

 0.0

how did this happen? since I am assigning the wrong value, should it not cause an error?

The biggest problem is this.

Since it automatically converts my validate method , it fails.

update - check method

 validate :is_dummy_number_valid, :the_dummy_number
 def is_dummy_number_valid
    read_attribute(:the_dummy_number).strip()
 end
+3
source share
1 answer

The reason this doesn't work, as you expect, is because the underlying Ruby BigDecimal implementation is not an error while passing a string.

Consider the following code

[ 'This is a string', '2is a string', '2.3 is also a string', 
  '   -3.3 is also a string'].each { |d| puts "#{d} = #{BigDecimal.new(d)}" }

This is a string = 0.0
2is a string = 2.0
2.3 is also a string = 2.3
   -3.3 is also a string = -3.3

BigDecimal - , .

class Dummy < ActiveRecord::Base

   validates_numericality_of :the_dummy_number

end

>> d=Dummy.new(:the_dummy_number => 'This is a string')
=> #<Dummy id: nil, the_dummy_number: #<BigDecimal:5b9230,'0.0',4(4)>, created_at: nil, updated_at: nil>

>> puts d.the_dummy_number
0.0
=> nil
>> d.valid?
=> false

>> d.errors
=> #<ActiveRecord::Errors:0x5af6b8 @errors=#<OrderedHash
  {"the_dummy_number"=>[#<ActiveRecord::Error:0x5ae114 
   @message=:not_a_number, @options={:value=>"This is a string"}

, validates_numericality_ raw_value, , typecast .

+3

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


All Articles