【问题标题】:Validation error involving numericality涉及数值的验证错误
【发布时间】:2014-04-06 13:39:32
【问题描述】:

我第一次使用验证,我正在尝试验证一个 amount_spent 和一个 no_of_purchases 字段,以便它只接受整数而不是字符串。所以 200 是有效的,但“两百”不是。但是,当我尝试进行此测试时,字符串部分失败,但我不确定为什么。这是我的 rspec 测试文件的 sn-p:

it 'requires a # of purchases' do
  customer = Customer.new(valid_customer.merge(no_of_purchases: ''))
  customer_2 = Customer.new(valid_customer.merge(no_of_purchases: 0))
  customer_3 = Customer.new(valid_customer.merge(no_of_purchases: 'twenty'))
  expect(customer).to_not be_valid
  expect(customer.errors[:no_of_purchases]).to include "can't be blank"
  expect(customer_2).to be_valid
  expect(customer_3).to_not be_valid
  expect(customer_3.errors[:no_of_purchases]).to include "is not a number"
end

it 'requires an amount spent' do
  customer = Customer.new(valid_customer.merge(amount_spent: ''))
  customer_2 = Customer.new(valid_customer.merge(no_of_purchases: 0))
  customer_3 = Customer.new(valid_customer.merge(no_of_purchases: 'twenty'))
  expect(customer).to_not be_valid
  expect(customer.errors[:amount_spent]).to include "can't be blank"
  expect(customer_2).to be_valid
  expect(customer_3).to_not be_valid
  expect(customer_3.errors[:no_of_purchases]).to include "is not a number"
end

这是我的模型文件:

 validates_presence_of :first_name
 validates_presence_of :last_name
 validates_presence_of :email
 validates_presence_of :no_of_purchases, numericality: true
 validates_presence_of :amount_spent, numericality: true

我没有看到错误。我已经指定数值为真,所以它不应该验证字符串。唯一可能是问题是我在我的模式文件中放置了一个默认值 0。我很确定这是问题所在,因为当我使用 binding.pry 时,客户 3 的 no_of_purchase,amount_spent 为 0 而不是“二十”。

问题 1:为什么要这样做? 问题 2:如何解决?

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails validation rspec


    【解决方案1】:

    乍一看,我可以看到您错误地使用了validates_presence_of。我不确定您使用的是什么版本的 Rails,但以下答案与 Rails 3 和 4 相关。

    让我们关注这两行:

    validates_presence_of :no_of_purchases, numericality: true
    validates_presence_of :amount_spent, numericality: true
    

    显式validates_something_of 验证一次只执行一项验证检查。对于validates_presence_of,您要求Rails 检查此属性的存在,而不是其他任何东西。附加 numericality: true 只是传入一个被忽略的选项哈希。这就是为什么您的数字检查在您的示例代码中不起作用的原因。

    要使其工作,我们可以使用内置的validates 方法将数值验证器应用于上述两个属性:

    validates :no_or_purchases, :amount_spent, numericality: true
    

    请注意,我没有添加明确的存在验证。默认情况下,这是内置在数值检查中的(因为 nil 不是数字!)。

    希望这会有所帮助。此外,Rails validation's documentation 解释了如何执行此操作,以及许多其他内置验证。

    【讨论】:

    • 感谢 phonk64。我使用的是 Rails 4,所以我想我所做的已经过时了。感谢您指出了这一点。非常感谢。
    • 没问题,很高兴能帮上忙!
    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2020-12-14
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    相关资源
    最近更新 更多