basic active record

15

Upload: kdmcclin

Post on 13-Aug-2015

25 views

Category:

Software


3 download

TRANSCRIPT

Basic Active Record Relationships

One-to-one, one-to-many, many-to-many

One to One

▪ The table of the belongs_to model contains a column with the foreign key (often id) of the has_one model

▪ Not always clear when to use one

▪ Users and social media profiles– A user only has_one

Facebook profile, and that profile only belongs_to that user

So when do I use it?

One indicator: the potential fora lot of null (empty) fields

One to Many

▪ Very common relationship

▪ Like one to one, the table of the belongs_to model contains a column with the foreign key (often id) of the has_many model

▪ Users and orders– A user has_many orders, and each order only belongs_to that

user

Many to Many

▪ Also very common

▪ Writing prompts and categories– Categories can contain many prompts, and those prompts can

belong to many categories

▪ Two ways of describing the relationship– has_many JOINTABLE & has_many OTHERTABLE through

JOINTABLE– has_and_belongs_to_many (Rails/ActiveRecord magic creates

the join table)

▪ Join table contains the foreign keys (ids) of what's connected to it

When to use has_and_belongs_to_many

When your join table only contains the foreign keys(ids)and no other useful information

When to use has_and_belongs_to_many

When your join table only contains the foreign keys(ids)and no other useful information

not conventional

When to use has_and_belongs_to_many

When your join table only contains the foreign keys(ids)and no other useful information

t.what_now?

▪ t.belongs_to, t.references, and t.integer– Everyone has their own preference, but any of these will work– t.belongs_to :user– t.references :user– t.integer :user_id▪ Note: when you use t.integer you need to specify the id because

integer just means a number▪ With t.belongs_to or t.references the Rails/ActiveRecord magic can

safely assume what you mean

More resources

▪ http://www.mutuallyhuman.com/blog/2014/06/12/activerecord-associations-and-you/

▪ http://guides.rubyonrails.org/association_basics.html

▪ https://github.com/kdmcclin/schema-practice

▪ https://github.com/kdmcclin/chained-relationships

@scarletalphabet