The 7th Round of ROR Lab.



Active Record
Associations - 1

     February 18th, 2012

       Hyoseong Choi
         ROR Lab.
For what?




            ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order


To delete orders




                     ROR Lab.
For what?


To add an order


To delete orders




                     ROR Lab.
For what?


• Automation of connecting btw models
• Automatic assignment of foreign key


                                    ROR Lab.
For what?
   Primary & Foreign Keys
customer               order
   id                       id




                                 ROR Lab.
For what?
     Primary & Foreign Keys
customer                 order
    id                        id
                      customer_id

parent obj.            child obj.


                                    ROR Lab.
For what?
     Primary & Foreign Keys
customer                        order
    id                             id
              Active Record   customer_id
               Assocation


parent obj.                    child obj.


                                            ROR Lab.
For what?




            ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order




                     ROR Lab.
For what?


To add an order

To delete orders




                     ROR Lab.
For what?


To add an order

To delete orders




                     ROR Lab.
Associations
             Parent Class        Child Class
               has_one
1 :1                             belongs_to
           has_one, :through
1 :n          has_many           belongs_to
                has_many
       A
           has_many B, :through
                                 belongs_to
n :m            has_many
       B
           has_many A, :through
             has_and_belongs_to_many
                                     ROR Lab.
Association Options
belongs_to options   has_one options   has_many options   HABTM options
• :autosave          • :as             • :as              • :association_foreign_key
• :class_name        • :autosave       • :autosave        • :autosave
• :conditions        • :class_name     • :class_name      • :class_name
• :counter_cache     • :conditions     • :conditions      • :conditions
• :dependent         • :dependent      • :counter_sql     • :counter_sql
• :foreign_key       • :foreign_key    • :dependent       • :delete_sql
• :include           • :include        • :extend          • :extend
• :polymorphic       • :order          • :finder_sql      • :finder_sql
• :readonly          • :primary_key    • :foreign_key     • :foreign_key
• :select            • :readonly       • :group           • :group
• :touch             • :select         • :include         • :include
• :validate          • :source         • :limit           • :insert_sql
                     • :source_type    • :offset          • :join_table
                     • :through        • :order           • :limit
                     • :validate       • :primary_key     • :offset
                                       • :readonly        • :order
                                       • :select          • :readonly
                                       • :source          • :select
                                       • :source_type     • :uniq
                                       • :through         • :validate
                                       • :uniq
                                       • :validate


                                                                   ROR Lab.
belongs_to vs
       has_one

• “belongs_to” model has a foreign key
• dependent upon the actual meaning of data


                                     ROR Lab.
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.


                                         ROR Lab.
Join Table
          HABTM
• Default join table btw Customer & Order
  models
  : custormers_orders
• Otherwise,
  :join_table => “join_table_name”



                                     ROR Lab.
Join Table
 HABTM




             ROR Lab.
Join Table
 HABTM



       no need for join model




                         ROR Lab.
Polymorphic
 Employee


       id


  Product


       id


              ROR Lab.
Polymorphic
 Employee   Picture

       id


  Product


       id


                      ROR Lab.
Polymorphic
 Employee       Picture

       id   employee_id



  Product


       id


                          ROR Lab.
Polymorphic
 Employee       Picture

       id   employee_id



  Product       Picture

       id


                          ROR Lab.
Polymorphic
 Employee       Picture

       id   employee_id



  Product       Picture

       id   product_id



                          ROR Lab.
Polymorphic
 Employee       Picture

       id   employee_id




       x
  Product       Picture

       id   product_id



                          ROR Lab.
Polymorphic
  Imageable       Picture

       id     imageable_id



  Imageable       Picture

       id     imageable_id



                             ROR Lab.
Polymorphic
  Imageable       Picture
  Employee

      id id   imageable_id



  Imageable       Picture
  Product

      id id   imageable_id



                             ROR Lab.
Polymorphic
  Model Class




                ROR Lab.
Polymorphic
  Migration




              ROR Lab.
Self Joins
• ex. : following or follower




                                ROR Lab.
Screencast
for Self Join


Please click the above link

                              ROR Lab.
:include
• To eager-load the second-order association




                                      ROR Lab.
:include
• To eager-load the second-order association
        @line_item.order.customer




                                      ROR Lab.
:include
• To eager-load the second-order association
        @line_item.order.customer




                                      ROR Lab.
:counter_cache


NT(*) from ...




                              ROR Lab.
:counter_cache


                 @customer.orders.size
NT(*) from ...




                                         ROR Lab.
:counter_cache


@customer.orders.size
           SELECT COUNT(*) from ...




                                  ROR Lab.
:counter_cache


@customer.orders.size
           SELECT COUNT(*) from ...




                                  ROR Lab.
:counter_cache
• But, you should add “orders_count”
  column to Customer model
• You can override the default column name.
• ReadOnly !!!



                                       ROR Lab.
:counter_cache
• But, you should add “orders_count”
  column to Customer model
• You can override the default column name.
• ReadOnly !!!



                                       ROR Lab.
Screencast for
   Belongs_to
:counter_cache

 Please click the above link

                               ROR Lab.
:touch
• Automatically set :updated_at
  or :update_on to current timestamp
  whenever child objects are saved or
  updated




                                        ROR Lab.
:touch




         ROR Lab.
:touch




         ROR Lab.
:touch



Or using a custom attribute




                              ROR Lab.
:touch



Or using a custom attribute




                              ROR Lab.
감사합니다.


                 ROR Lab.

More Related Content

KEY
ActiveRecord Associations (2), Season 1
KEY
ActiveRecord Association (1), Season 2
PPT
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
KEY
Active Record Association (2), Season 2
KEY
Active Record Validations, Season 1
KEY
ActiveRecord Validations, Season 2
KEY
Action Controller Overview, Season 1
KEY
Routing 1, Season 1
ActiveRecord Associations (2), Season 1
ActiveRecord Association (1), Season 2
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Active Record Association (2), Season 2
Active Record Validations, Season 1
ActiveRecord Validations, Season 2
Action Controller Overview, Season 1
Routing 1, Season 1

Similar to ActiveRecord Associations (1), Season 1 (20)

KEY
Testing gone-right
KEY
Active Record Form Helpers, Season 1
PPT
My experience in Software QA
KEY
Refactoring RIA Unleashed 2011
PPTX
My Little Webap - DevOpsSec is Magic
PDF
Functional Ruby
PDF
Funtional Ruby - Mikhail Bortnyk
PDF
Spring framework
PDF
Tackling Testing Telephony
KEY
ActiveRecord Callbacks & Observers, Season 2
KEY
Message passing
KEY
Developer testing 201: When to Mock and When to Integrate
PPT
Andrew Polaszek - ZooBank: ICZN’s open-access web register of animal names a...
KEY
Active Model
PDF
ITB2017 - Slaying the ORM dragons with cborm
PPTX
Drupal commerce performance profiling and tunning using loadstorm experiments...
KEY
WTF TDD?
PPT
'An Evolution Into Specification By Example' by Adam Knight
PPTX
Libraries and Linked Data: Looking to the Future (2)
ZIP
44 Slides About 22 Modules
Testing gone-right
Active Record Form Helpers, Season 1
My experience in Software QA
Refactoring RIA Unleashed 2011
My Little Webap - DevOpsSec is Magic
Functional Ruby
Funtional Ruby - Mikhail Bortnyk
Spring framework
Tackling Testing Telephony
ActiveRecord Callbacks & Observers, Season 2
Message passing
Developer testing 201: When to Mock and When to Integrate
Andrew Polaszek - ZooBank: ICZN’s open-access web register of animal names a...
Active Model
ITB2017 - Slaying the ORM dragons with cborm
Drupal commerce performance profiling and tunning using loadstorm experiments...
WTF TDD?
'An Evolution Into Specification By Example' by Adam Knight
Libraries and Linked Data: Looking to the Future (2)
44 Slides About 22 Modules
Ad

More from RORLAB (20)

PDF
Getting Started with Rails (4)
PDF
Getting Started with Rails (3)
PDF
Getting Started with Rails (2)
PDF
Getting Started with Rails (1)
PDF
Self join in active record association
PDF
Asset Pipeline in Ruby on Rails
PDF
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
PDF
Active Support Core Extension (3)
PDF
Active Support Core Extension (2)
PDF
Active Support Core Extensions (1)
PDF
Action Controller Overview, Season 2
PDF
Action View Form Helpers - 2, Season 2
PDF
Action View Form Helpers - 1, Season 2
PDF
Layouts and Rendering in Rails, Season 2
PDF
ActiveRecord Query Interface (2), Season 2
KEY
Active Record Query Interface (1), Season 2
KEY
Rails Database Migration, Season 2
KEY
Getting started with Rails (4), Season 2
KEY
Getting started with Rails (3), Season 2
KEY
Getting started with Rails (2), Season 2
Getting Started with Rails (4)
Getting Started with Rails (3)
Getting Started with Rails (2)
Getting Started with Rails (1)
Self join in active record association
Asset Pipeline in Ruby on Rails
레일스가이드 한글번역 공개프로젝트 RORLabGuides 소개
Active Support Core Extension (3)
Active Support Core Extension (2)
Active Support Core Extensions (1)
Action Controller Overview, Season 2
Action View Form Helpers - 2, Season 2
Action View Form Helpers - 1, Season 2
Layouts and Rendering in Rails, Season 2
ActiveRecord Query Interface (2), Season 2
Active Record Query Interface (1), Season 2
Rails Database Migration, Season 2
Getting started with Rails (4), Season 2
Getting started with Rails (3), Season 2
Getting started with Rails (2), Season 2
Ad

Recently uploaded (20)

PDF
advance database management system book.pdf
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PPTX
Computer Architecture Input Output Memory.pptx
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
PDF
Hazard Identification & Risk Assessment .pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
English Textual Question & Ans (12th Class).pdf
PPTX
Core Concepts of Personalized Learning and Virtual Learning Environments
PDF
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
Complications of Minimal Access-Surgery.pdf
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PDF
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PPTX
Virtual and Augmented Reality in Current Scenario
PDF
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
PDF
What if we spent less time fighting change, and more time building what’s rig...
advance database management system book.pdf
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Computer Architecture Input Output Memory.pptx
A powerpoint presentation on the Revised K-10 Science Shaping Paper
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
Hazard Identification & Risk Assessment .pdf
Environmental Education MCQ BD2EE - Share Source.pdf
English Textual Question & Ans (12th Class).pdf
Core Concepts of Personalized Learning and Virtual Learning Environments
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
Empowerment Technology for Senior High School Guide
Complications of Minimal Access-Surgery.pdf
FORM 1 BIOLOGY MIND MAPS and their schemes
Mucosal Drug Delivery system_NDDS_BPHARMACY__SEM VII_PCI.pdf
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
Virtual and Augmented Reality in Current Scenario
1.3 FINAL REVISED K-10 PE and Health CG 2023 Grades 4-10 (1).pdf
What if we spent less time fighting change, and more time building what’s rig...

ActiveRecord Associations (1), Season 1

Editor's Notes