Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ActiveRecord Associations(1) - RORLab Season 3-7

ActiveRecord Associations(1) - RORLab Season 3-7

seapy

May 25, 2013
Tweet

More Decks by seapy

Other Decks in Programming

Transcript

  1. Active Record Associations (1) Ror lab. season 3 - the

    7th round - May 24, 2013 ChangHoon Jeong(@seapy)
  2. The Reason why we should use Active Record Associations •

    Automation of connecting btw models • Automatic assignment of foreign key
  3. Using Active Record Associations customer order customer_id id id id

    parent obj. child obj. Active Record Assocation Primary & Foreign Keys
  4. Associations Parent Class Parent Class Parent Class Child Class 1

    : 1 has_one has_one has_one belongs_to 1 : 1 has_one, :through has_one, :through has_one, :through belongs_to 1 : n has_many has_many has_many belongs_to n : m A has_many has_many belongs_to n : m A has_many B, :through has_many B, :through belongs_to n : m B has_many has_many belongs_to n : m B has_many A, :through has_many A, :through belongs_to n : m A / B A / B has_and_belongs_to_many has_and_belongs_to_many C
  5. belongs_to vs has_one • “belongs_to” model has a foreign key

    • dependent upon the actual meaning of data
  6. has_many :through vs has_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.
  7. Join Table HABTM • Default join table btw Customer &

    Order models : custormers_orders • Otherwise, :join_table => “join_table_name”