4

我正在使用 Ruby 1.9.3-p448 和 Rails 3.2.13。我有一个带有浮点格式验证的简单模型:

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  field :height, type: Float
  field :weight, type: Float

  validates :height, presence: true, format: { with: /[-+]?[0-9]*\.?[0-9]+/ }
  validates :weight, presence: true, format: { with: /[-+]?[0-9]*\.?[0-9]+/ }

end

如果我运行此代码:

test = User.new(height:"hi", weight:"try")

它给了我以下结果:

#<User _id: 51f67b49781018056b000008, created_at: nil, updated_at: nil, height: 0.0,width: 0.0> 

如果我放一个字符串,为什么 mongoid 会放一个 0.0 值?我期待一个验证错误。

4

2 回答 2

3

您没有收到验证错误,因为该方法new不会触发验证,要查看它,您应该执行:

User.create!(height:"hi", weight:"try")
# .../mongoid-3.1.0/lib/mongoid/persistence.rb:335:in `fail_validate!': (Mongoid::Errors::Validations)
# Problem:
#   Validation of User failed.
# Summary:
#   The following errors were found: Height is invalid, Weight is invalid
# ...

鉴于此,字段heightweight被填充,0.0因为Strings 被转换为Float使用该to_f方法,其行为如下:

'foo'.to_f
# => 0.0

此外,使用正则表达式验证浮点字段是没有用的,因为转换Float是在验证之前执行的,所以验证总是因为以下行为而失败=~

1.2 =~ /any_regexp/
# => nil


更新要验证,以字符串形式给出,该字段是一个有效数字,您可以使用以下numericality选项:

class User
  # ...
  validates :height, presence: true, numericality: true
  # ...
end

User.create!(height: '0.0')
# => #<User ... >

User.create!(height: 'foo')
# Problem:
#  Validation of User failed.
# ...
于 2013-07-29T15:20:38.830 回答
-1

MongoDB 以称为 BSON 的二进制格式存储数据,该格式支持以下数字数据类型:

  • int32- 4 个字节(32 位有符号整数)
  • int64- 8 字节(64 位有符号整数)
  • double- 8 字节(64 位 IEEE 754 浮点)

MongoDB 中没有与 mySQL 的小数类型等效的精确值定点,但您可以在 Mongo 中将 64 位浮点数存储为双精度数。

值得一提的是,MongoDB shell - 作为一个 JavaScript shell - 不识别整数和浮点值之间的区别,它对待所有数字都是一样的,因为 JavaScript 将所有数字表示为 64 位浮点,而不管它们的底层 BSON类型。

然而,大多数MongoDB 语言驱动程序都区分整数和浮点类型。

从 -> MongoDB 是否支持浮点类型?

于 2013-07-29T14:41:15.250 回答