Chennai-Rails Workshop
21 March 2015
Abhishek Yadav
@h6165
one-many
one-one
many-many
Team
Player
team_id
Team
has_many :players
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:
Player belongs_to :team
So we can do:
player.team player.team = Team.last
Team
Coach
team_id
Team
has_one :coach
Team
has_one :coach
We can do -
team.coach
team.coach = Coach.find (2)
team.coach.create(name: 'Steve')
Person
Match
Person watches many matches
Match has many people watching
Person watches many matches
Match has many people watching
Should have a join table
matches_people
person_id
match_id
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
Person has_many :matches, through: :matches_people has_many :matches_people Match has_many :persons, through: :matches_people has_many :matches_people
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')
Person has_and_belongs_to_many :matches Match has_and_belong_to_many :people
has_and_belongs_to_many
http://guides.rubyonrails.org/association_basics.html