红宝石-Rails验证需要数字,即使状态未设置为tru

我正在尝试保存没有一个字段集的记录-该记录在模型中具有有效的数值。 即使验证中不需要存在,它仍会引发错误,表明该字段不是数字。

验证:

validates :network_id,    :numericality => true

保存模型的代码:

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

错误:

Validation failed: Network is not a number
Hopstream asked 2019-10-08T10:21:26Z
5个解决方案
119 votes
validates :network_id, :numericality => true, :allow_nil => true
Unixmonkey answered 2019-10-08T10:21:30Z
40 votes
    validates :network_id, :numericality => {:allow_blank => true}
p.matsinopoulos answered 2019-10-08T10:21:47Z
15 votes

您应该使用allow_blank

validates :network_id,    :numericality => true, :allow_blank => true
apneadiving answered 2019-10-08T10:22:10Z
10 votes

在Rails 4(Ruby 2)中,您可以编写:

validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
sergserg answered 2019-10-08T10:22:34Z
0 votes

您也可以这样写...

validates_numericality_of :network_id, allow_nil: true
thedanotto answered 2019-10-08T10:22:57Z
translate from https://stackoverflow.com:/questions/7981351/rails-validation-required-numericality-even-though-presence-is-not-set-to-true