12. Associations
Parent Class Child Class
has_one
1 :1 belongs_to
has_one, :through
1 :n has_many belongs_to
has_many
A C
has_many B, :through
n :m has_many belongs_to
B
has_many A, :through
A/B has_and_belongs_to_many
14. belongs_to vs
has_one
• “belongs_to” model has a foreign key
• dependent upon the actual meaning of data
15. 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.
44. :counter_cache
• But, you should add “orders_count” column to Customer model
• Default column name : table name + “_count”
• You can override the default column name.
• ReadOnly !!!
45. :counter_cache
• But, you should add “orders_count” column to Customer model
• Default column name : table name + “_count”
• You can override the default column name.
• ReadOnly !!!
46. Screencast for
Belongs_to
:counter_cache
Please click the above link
47. :touch
• Automatically set :updated_at
or :update_on to current timestamp
whenever child objects are saved or
updated