Rails validation required numericality even though

2020-08-09 07:42发布

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

5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-08-09 07:47

You should use allow_blank

validates :network_id,    :numericality => true, :allow_blank => true
查看更多
The star\"
3楼-- · 2020-08-09 07:57

You can also write like this...

validates_numericality_of :network_id, allow_nil: true
查看更多
别忘想泡老子
4楼-- · 2020-08-09 08:02
validates :network_id, :numericality => true, :allow_nil => true
查看更多
做个烂人
5楼-- · 2020-08-09 08:05
    validates :network_id, :numericality => {:allow_blank => true}
查看更多
霸刀☆藐视天下
6楼-- · 2020-08-09 08:09

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

validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
查看更多
登录 后发表回答