Skip to content

Foreign key cop false-positive

A new foreign key cop was added in !40858 (merged). It's supposed to catch when developers add multiple foreign keys for a single table.

However, in an MR at !39652 (merged) it's creating a false-positive.

Migration

def up
    unless table_exists?(:authentication_events)
      with_lock_retries do
        create_table :authentication_events do |t|
          t.inet :ip_address
          t.datetime_with_timezone :created_at, null: false
          t.references :user, foreign_key: { on_delete: :nullify }, index: true
          t.integer :result, limit: 2, null: false
          t.text :provider, null: false, index: true
          t.text :user_name, null: false
        end
      end
    end

    add_text_limit :authentication_events, :provider, 64
    add_text_limit :authentication_events, :user_name, 255
  end

The static-analysis job fails with:

Offenses:
db/migrate/20200908100053_create_authentication_events.rb:13:9: C: Migration/CreateTableWithForeignKeys: Creating a table with more than one foreign key at once violates our migration style guide. For more details check the https://docs.gitlab.com/ce/development/migration_style_guide.html#examples
        create_table :authentication_events do |t|
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
18466 files inspected, 1 offense detected

Interestingly, if I add to_table: 'users' to the foreign key line the cop is happy. This shouldn't be necessary for this case.

cc/ @minac @tigerwnz