Active RecordAssociations (1)Ror lab. season 3- the 7th round -May 24, 2013ChangHoon Jeong(@seapy)
No AssociationsTo add an orderTo delete a customer
The Reason whywe should useActive RecordAssociations• Automation of connecting btw models• Automatic assignment of foreign key
Using Active RecordAssociationscustomer ordercustomer_idid ididparent obj. child obj.Active RecordAssocationPrimary & Foreign Keys
With AssociationsTo add an orderTo delete a customer
AssociationsParent ClassParent ClassParent Class Child Class1 : 1has_onehas_onehas_onebelongs_to1 : 1has_one, :throughhas_one, :throughhas_one, :throughbelongs_to1 : n has_manyhas_manyhas_many belongs_ton : mAhas_manyhas_manybelongs_ton : mAhas_many B, :throughhas_many B, :throughbelongs_ton : mBhas_manyhas_many belongs_ton : mBhas_many A, :throughhas_many A, :throughbelongs_ton : mA / BA / B has_and_belongs_to_manyhas_and_belongs_to_manyC
belongs_to vshas_one• “belongs_to” model has a foreign key• dependent upon the actual meaning of data
has_many :through vshas_and_belongs_to_many๏ has_many- validations, callbacks, or extra attributes๏ has_and_belongs_to_many- no need for additional functionalities- should create a “join” table in the DB.