Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 773
Hopstream Avatar asked Nov 02 '11 13:11

Hopstream


4 Answers

validates :network_id, :numericality => true, :allow_nil => true
like image 55
Unixmonkey Avatar answered Nov 18 '22 15:11

Unixmonkey


    validates :network_id, :numericality => {:allow_blank => true}
like image 27
p.matsinopoulos Avatar answered Nov 18 '22 16:11

p.matsinopoulos


You should use allow_blank

validates :network_id,    :numericality => true, :allow_blank => true
like image 16
apneadiving Avatar answered Nov 18 '22 15:11

apneadiving


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

validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
like image 11
sergserg Avatar answered Nov 18 '22 15:11

sergserg