rails/rails — Issue #3277: ActiveRecord::RecordNotUnique not always raised
Author: fphilipe
Created: 2011-10-10 09:58:51+00:00
State: open

Creating a record that violates a unique constraint in a SQLite database should raise `ActiveRecord::RecordNotUnique`.

What I observed is the following:

```ruby
TestModel.create(name: 'test') # => persisted record

x = TestModel.new(name: 'test')
x.save # => ActiveRecord::StatementInvalid: SQLite3::ConstraintException: constraint failed
x.save # => ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: column name is not unique
x.save # => ActiveRecord::StatementInvalid: SQLite3::ConstraintException: constraint failed
x.save # => ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: column name is not unique
```

The raised exception alternates starting with `ActiveRecord::StatementInvalid` followed by `ActiveRecord::RecordNotUnique`.

Executing raw SQL always raises `ActiveRecord::RecordNotUnique` as expected:

```ruby
TestModel.connection.execute('INSERT INTO "test_models" ("name") VALUES ("test")')
# => ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: column name is not unique
TestModel.connection.execute('INSERT INTO "test_models" ("name") VALUES ("test")')
# => ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: column name is not unique
```

The app was created with `rails new someapp` and the migration for the model used is:

```ruby
class CreateTestModels < ActiveRecord::Migration
def change
create_table :test_models do |t|
t.string :name

t.timestamps
end

add_index :test_models, :name, unique: true
end
end
```

Anyone else observing this weird behavior?