Skip to content

Non-incrementing IDs cause problems with unique indexes #51

@gcpreston

Description

@gcpreston

The error: ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'


I have a table with a polymorphic unique relationship:

create_table :entities do |t|
  t.references :entityable, null: false, polymorphic: true, index: { unique: true }
end

I've implemented the logic for this relationship in a Concern (called Entityable). This involves creating an associated Entity automatically on creation of a model which includes Entityable:

before_validation -> { Entity.create!(entityable: self) if entity.nil? }, on: :create

I'm using with_model to test this Concern outside of an existing model:

class EntityableTest < ActiveSupport::TestCase
  with_model :FakeRecord do
    table do |t|
      t.string :name
    end

    model do
      include Concerns::Entityable
    end
  end

  def test_something
    record = FakeRecord.create!(name: 'test')
    # assert that this creates an Entity correctly...
  end
end

Here, the test passes on the first run, but on subsequent runs, calling FakeRecord.create! gives the error ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'FakeRecord-1' for key 'index_entities_on_entityable'. It seems that what's happening is a FakeRecord with ID of 1 is trying to be created, and an index entry already exists for that.

This is strange to me for 2 reasons:

  1. I know that when creating regular ActiveRecord models, the IDs are incremented even between test runs, so this issue doesn't occur.
  2. I would think that indexes are cleared out between runs similar to how tables are, but maybe this is not the case.

Regardless, it would seem that the fix for this would be incrementing model IDs rather than restarting from 1 each time. In the meantime, it seems impossible to effectively test unique indexes via with_model.

Please let me if there is any need for clarification. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions