Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-5843

NoMethodError raise with validates_numericality_of is used with BigDecimal

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Unknown Unknown
    • 9.0.7, 8.1.11, 8.0.11
    • Affects Version/s: 8.0.9, 8.1.9, 9.0.5
    • Component/s: None
    • None
    • None
    • Fully Compatible
    • Ruby Drivers
    • Not Needed
    • None
    • None
    • None
    • None
    • None
    • None

      When `validates_numericality_of` is used with a BigDecimal field and the model is saved twice, an undefined method error is raised.

      require 'bundler/inline'
      
      gemfile do
        source 'https://rubygems.org'
      
        gem 'mongoid', '~> 9.0'
        gem 'activemodel', '~> 7.2.0'
      end
      
      Mongoid.configure do |config|
        config.clients.default = {
          hosts: ['mongo:27017'],
          database: 'mongoid_test',
        }
        config.map_big_decimal_to_decimal128 = true
      end
      Mongoid.purge!
      
      class Article
        include Mongoid::Document
      
        field :send_delay, type: BigDecimal, default: 0
      
        validates_numericality_of :send_delay
      end
      
      article = Article.new(send_delay: '0')
      
      pp article.save! # => true
      pp article.save!
      # => /usr/local/bundle/gems/activemodel-7.2.2.1/lib/active_model/validations/numericality.rb:80:in `parse_as_number': undefined method `to_i' for BSON::Decimal128('0'):BSON::Decimal128 (NoMethodError)
      

      It happens because in this line, raw_value is a string the first time and a ::BSON::Decimal128 the second time.

      Changing config.map_big_decimal_to_decimal128 to false fix the issue, but the value is true by default.

            Assignee:
            jamis.buck@mongodb.com Jamis Buck
            Reporter:
            guirec.corbel@gmail.com Guirec Corbel
            Votes:
            1 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved:
              None
              None
              None
              None