创建一个 rails 记录,其字符串值为整数集 nil 静默

Creating a rails record with string value for integer sets nil silently

在我的 rails (4.2.1) 应用程序中,我有一个带有整数字段 fooPost 模型。在创建 post 时,我将一个字符串传递给整数字段。我预计会出现错误,但创建记录时 foo 设置为 nil。为什么我没有得到错误?

# migration
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :name
      t.integer :foo

      t.timestamps null: false
    end
  end
end

# post creation, no error ???
Post.create!(name: 'a post', foo: 'a_string')

# post has nil value in foo
Post.first
#=> Post id: 1, name: "a post", foo: nil, ...

实际上,我想为 Post 编写一个失败的测试,然后我将 foo 更改为枚举以使测试通过。我很惊讶测试没有引发错误。

这是数据库的 "feature"。 Rails 此时不知道属性的类型。如果你想让它只接受整数,你可以使用 validates_numericality_of :foo.

如果你想让你的测试在它不是枚举时失败,你可以这样做

expect { subject.foo = 'invalid value' }.to raise_exception(ArgumentError)

只要它不是枚举,它就会失败。