Skip to content

Disallow create_table without primary key #1391

Open
@kapcod

Description

@kapcod

Is your feature request related to a problem? Please describe.

Currently Rubocop doesn't check if primary key is defined on the table and before Rails 7.1 there was no documented way of creating custom primary keys, so people used id: :false and later alter_table. However since Rails 7.1 there's a convenient way to define primary keys and it's, IMHO, the most readable and convenient way. Creating tables without primary keys can lead to performance issues and unexpected issues with ActiveRecord behavior. Some people create unique indexes instead, but sometimes make them NULLable by mistake which breaks uniqueness and thus cannot be used as real primary key by the DB.

Describe the solution you'd like

I suggest to create cop that forbids id parameter (including id: false) in favor of primary_key: :my_key to create standard autoincremented bigint called "my_key" or primary_key: [:my_key] to just make one or more keys primary key, assuming they're defined in the table block.
By just disallowing id we ensure there is some primary key because there's no other way to prevent the table from having it.

Describe alternatives you've considered

I considered allowing id: false in the options of create_table but only if inside there's a column with primary_key: true option, or t.primary_key :my_key line, but this seems more complicated relative to just preventing id: false.

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