ER

## One-to-One Association

• One person has exactly one personal_info entry
• One personal_info entry belongs to exactly one person
• The “belongs to” side is the one with a foreign key

db/migrate/_create_personal_info.rb

app/models/person.rb

app/models/personal_info.rb

### More Methods

you have build_personal_info(hash) and create_personal_info(hash) methods on a person instance

## One-to-Many Association

• One person has one or more jobs
• One job entry belongs to exactly one person
• The “belongs to” side is the one with a foreign key

db/migrate/_create_jobs.rb

app/models/person.rb

app/models/job.rb

### More Methods

• person.jobs = jobs
• person.jobs << job(s)
• person.jobs.clear

## Many-to-Many

• One person can have many hobbies
• One hobby can be shared by many people
• Need to create an extra (a.k.a. join) table (without a model, i.e. just a migration)
• Convention: Plural model names separated by an underscore in alphabetical order

db/migrate/_create_habbies_people.rb

app/models/person.rb

app/models/hobby.rb

## Rich Many-to-Many Association

• Sometimes, you need to keep some data on the join table
• You need to store grandchild relationships on a model, like Person -> Job -> SalaryRange
• ActiveRecord provides a :through option for this purpose
• Basic idea: you first create a regular parent-child relationship and then use the child model as a join between the parent and grandchild.

db/migrate/_create_salary_ranges.rb

app/models/salary_range.rb

app/models/job.rb

app/models/person.rb