---
# System prepended metadata

title: Active Record Associations
tags: [Gemcamp]

---

# Active Record Associations


1. **One-to-One Relationship**
A one-to-one association exists when one record in a model is related to only one record in another model.

Example: If a user has a single profile:

A User has one Profile, and a Profile belongs to a User.

```ruby=
class User < ApplicationRecord
  has_one :profile
end

class Profile < ApplicationRecord
  belongs_to :user
end
```

```
rails generate model User name:string email:string
rails generate model Profile image:text user:references
```

2. One-to-Many Relationship 

```ruby=
class School < ApplicationRecord
  has_many :students
end


class Student < ApplicationRecord
  belongs_to :school
end
```

3. Many-to-Many Relationship 

In a many-to-many relationship, multiple records in one model can be associated with multiple records in another model.

Example: A Project can have many Developers, and a Developer can work on many Projects. This is usually achieved using a join table.

```ruby=
rails generate model Developer name:string
rails generate model Project title:string
rails generate model DeveloperProject developer:references project:references
```

```ruby=
class Developer < ApplicationRecord
  has_many :developer_projects
  has_many :projects, through: :developer_projects
end

class DeveloperProject < ApplicationRecord
  belongs_to :developer
  belongs_to :project
end

class Project < ApplicationRecord
  has_many :developer_projects
  has_many :developers, through: :developer_projects
end
```


## Special Associations 

A polymorphic association allows a model to belong to more than one other model on a single association.

Example: A Comment can belong to both a Post and a Photo.

```ruby=
rails generate model Comment body:text commentable:references{polymorphic}
rails generate model Post title:string
rails generate model Photo title:string
```

```ruby=
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

class Post < ApplicationRecord
  has_many :comments, as: :commentable
end

class Photo < ApplicationRecord
  has_many :comments, as: :commentable
end
```

### Types of Associations

**belongs_to** Indicates a relationship where the model contains the foreign key.
**has_one**: Specifies that a model has one of something.
**has_many**: Specifies that a model has many related records.
**has_many through**: Specifies a many-to-many relationship using a join table.
**has_one through**: Allows a one-to-one relationship through another model.
**has_and_belongs_to_many**: Used for many-to-many relationships without a separate join model.





