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


in rails (4.2.1) app, have post model integer field foo. while creating post, passed string integer field. expected error, record got created foo set nil. why don't error?

# migration class createposts < activerecord::migration   def change     create_table :posts |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, wanted write failing test post, , change foo enum make test pass. surprised test did not raise error.

it's "feature" of db. rails @ point doesn't know type of attribute. if want accept integers, can use validates_numericality_of :foo.

if want test fail while it's not enum, like

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

that way fail long it's not enum.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -