Anand
Anand

Reputation: 3760

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

In my rails (4.2.1) app, I have a Post model with an integer field foo. While creating a post, I passed a string to the integer field. I expected an error, but the record got created with foo set to nil. Why don't I get 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 the Post, and then I would change foo to be an enum to make the test pass. I was surprised that the test did not raise an error.

Upvotes: 3

Views: 1518

Answers (1)

Marcus Ilgner
Marcus Ilgner

Reputation: 7231

It's a "feature" of the db. Rails at this point doesn't know about the type of the attribute. If you want it to only accept integers, you can use validates_numericality_of :foo.

If you want your test to fail while it's not an enum, you could do something like

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

that way it will fail as long as it's not an enum.

Upvotes: 6

Related Questions