---
title: Prefer has_many :through over HABTM
impact: MEDIUM
impactDescription: Allow for additional attributes and validations on join models.
tags: rails, database, associations, active-record
---

## Prefer has_many :through over HABTM

Allow for additional attributes and validations on join models. Use `has_many :through` instead of `has_and_belongs_to_many` for many-to-many relationships. This provides more flexibility for adding attributes or validations to the join table later.

**Incorrect:**

```ruby
class User < ApplicationRecord
  has_and_belongs_to_many :roles
end
```

**Correct:**

```ruby
class User < ApplicationRecord
  has_many :assignments
  has_many :roles, through: :assignments
end

class Assignment < ApplicationRecord
  belongs_to :user
  belongs_to :role
  # Can add validations or extra fields here
end
```

**Tools:** RuboCop (`Rails/HasAndBelongsToMany`)
