Rails validation required numericality even though presence is not set to true

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


I'm trying to save a record which doesn't have one field set -- which has a validate numericality in the models. Even though the presence is not required in the validation, it's still throwing an error that the field is not a number.

Validation:

validates :network_id,    :numericality => true

Code to that is saving model:

networks.each do |network|
  network.url = network.raw_data.link
  network.save!
end

Error:

Validation failed: Network is not a number

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

validates :network_id, :numericality => true, :allow_nil => true

Solution 2 - Ruby on-Rails

    validates :network_id, :numericality => {:allow_blank => true}

Solution 3 - Ruby on-Rails

You should use allow_blank

validates :network_id,    :numericality => true, :allow_blank => true

Solution 4 - Ruby on-Rails

In Rails 4 (Ruby 2), you can write:

validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }

Solution 5 - Ruby on-Rails

You can also write like this...

validates_numericality_of :network_id, allow_nil: true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHopstreamView Question on Stackoverflow
Solution 1 - Ruby on-RailsUnixmonkeyView Answer on Stackoverflow
Solution 2 - Ruby on-Railsp.matsinopoulosView Answer on Stackoverflow
Solution 3 - Ruby on-RailsapneadivingView Answer on Stackoverflow
Solution 4 - Ruby on-RailssergsergView Answer on Stackoverflow
Solution 5 - Ruby on-RailsthedanottoView Answer on Stackoverflow