Rails Coach

Model Associations


Listen Later

ActiveRecord models are based upon tables in relational databases. This, of course, means that they can be relational. Models can associate in three main ways: one to many, one to one, and many to many.
One to many is usually achieved by calling has_many on the model representing the “one” to state that it “has many” of its counterparts. The model that represents the “many” calls
belongs_to . Here’s an example:
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :user
end
In addition, the model that represents the “many” needs a reference column or foreign key for the “one”. In this case, the posts table would have a user_id column.
One to one works the same way one to many works except it uses has_one instead of has_many.
Many to many is implemented in one of two different ways. The first--and generally default--way of doing this is has_and_belongs_to_many. As you can imagine, this is used just like has_many or belongs_to except you call it in both models.
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
end
...more
View all episodesView all episodes
Download on the App Store

Rails CoachBy Charles Max Wood

  • 4.7
  • 4.7
  • 4.7
  • 4.7
  • 4.7

4.7

3 ratings


More shows like Rails Coach

View all
Teach Me To Code » Screencasts by Charles Max Wood

Teach Me To Code » Screencasts

11 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

234 Listeners

iPhreaks by Charles M Wood

iPhreaks

17 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

45 Listeners

The Freelancers' Show by Charles M Wood

The Freelancers' Show

23 Listeners

React Native Radio by Jamon Holmgren, Robin Heinze, Mazen Chami

React Native Radio

59 Listeners

My JavaScript Story by Charles M Wood

My JavaScript Story

4 Listeners

JavaScript Jabber by Charles M Wood

JavaScript Jabber

62 Listeners

Ruby Rogues by Charles M Wood

Ruby Rogues

21 Listeners

Adventures in Angular by Charles M Wood

Adventures in Angular

15 Listeners