Create rails entry with string value for integer nil sets silently
In my rails (4.2.1) application, I have a model Post
with an integer field foo
. When creating a post, I passed a string to a whole field. I expected an error, but the entry was created using the foo
set to nil
. Why am I not getting an error?
# 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, ...
Actually, I wanted to write a failing test for Post, and then I would change foo to enum to make the test pass. I was surprised the test didn't throw an error.
source to share
This is a "feature" of db. Rails at this point are unaware of the attribute type. If you want it to only accept integers, you can use validates_numericality_of :foo
.
If you want your test to fail while it is not an enum, you can do something like
expect { subject.foo = 'invalid value' }.to raise_exception(ArgumentError)
thus it will fail if it is not an enumeration.
source to share