rails-composite-keys
Installation
SKILL.md
Rails Composite Keys
When to Use
- Use composite primary keys when uniqueness must span multiple columns
- Avoid them unless your data model or legacy database demands it
Migrations
- Use
primary_key: %i[key1 key2]when creating the table - Do not use
t.primary_key :id— Rails will create a single-column ID instead - Omit
id: falsewhen using theprimary_key:option directly oncreate_table
Model Declarations
- Rails 7.1+ ships native composite keys — no gem required
- Use
self.primary_key = [:user_id, :group_id]on the model - For non-PK composite identity (e.g. tenant-scoped records with surrogate
id), usequery_constraints :tenant_id, :idso all generated SQL scopes by the full tuple