Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-incrementing IDs cause problems with unique indexes #51

Open
gcpreston opened this issue May 9, 2024 · 0 comments
Open

Non-incrementing IDs cause problems with unique indexes #51

gcpreston opened this issue May 9, 2024 · 0 comments

Comments

@gcpreston
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant