ActiveRecord Associations
Chennai-Rails Workshop
21 March 2015
Abhishek Yadav
@h6165
Database Relationships
one-many
one-one
many-many
One to many
Team
Player
team_id
One to many
Team
has_many :players
- We declare in Team model
- Rails guesses it refers to the Player model
- Rails guesses there's a 'team_id' in 'players' table
One to many
Team has_many :players
team.players = Player.find(2,3,4) team.players team.players.create(name: 'Abhi') team.players.where(name: 'Abhi') team.players.destroy
So we can do:
One to many
Player belongs_to :team
So we can do:
- We declare in Player model
- Rails guesses it refers to the Team model
- Rails guesses there's a 'team_id' in 'teams' table
player.team player.team = Team.last
One to one
Team
Coach
team_id
One to one
Team
has_one :coach
- We declare in Team model
- Rails guesses it refers to the Coach model
- Rails guesses there's a 'team_id' in 'coaches' table
One to one
Team
has_one :coach
We can do -
team.coach
team.coach = Coach.find (2)
team.coach.create(name: 'Steve')
Many to many
Person
Match
Person watches many matches
Match has many people watching
Many to many
Person watches many matches
Match has many people watching
Should have a join table
matches_people
person_id
match_id
Many to many
Person
has_many :matches, through: :matches_people
has_many :matches_people
Match
has_many :people, through: :matches_people
has_many :matches_people
MatchesPerson
belongs_to :matches
belongs_to :person
has_many :through
Many to many
Person has_many :matches, through: :matches_people has_many :matches_people Match has_many :persons, through: :matches_people has_many :matches_people
- Rails figures that there is a join table called matches_people
- Rails assumes it has person_id and match_id fields in it.
Many to many
Person
has_many :matches, through: :matches_people
has_many :matches_people
Match
has_many :persons, through: :matches_people
has_many :matches_people
We can do:
match.persons = Person.find(1,2,3)
match.persons << Person.find(4,5,6)
person.matches << Match.where(team1: 'India')
Many to many
Person has_and_belongs_to_many :matches Match has_and_belong_to_many :people
- Join table matches_persons should be created separately
- Join table is not a model
has_and_belongs_to_many
More:
http://guides.rubyonrails.org/association_basics.html
ActiveRecord Associations
By Abhishek Yadav
ActiveRecord Associations
- 1,051