active-record-associations
Installation
SKILL.md
Active Record Associations Expert
Define correct, performant, and maintainable associations between Rails models.
Philosophy
Core Principles:
- The FK lives on the
belongs_toside — always. If you're confused about where it goes, ask "which table has the_idcolumn?" That model getsbelongs_to. - Always set
dependent:— orphaned records are bugs waiting to happen. - Prefer
has_many :throughoverhas_and_belongs_to_many— every time. HABTM is a dead end you'll regret. - Bi-directional by default — declare both sides. Use
inverse_ofwhen Rails can't infer it. - Eager load aggressively — N+1 queries are the #1 performance killer in Rails apps.
- Database constraints back up model associations — foreign keys, indexes, and unique constraints belong in migrations, not just models.