Associations in Ruby for dummies (with kitty pics)

belongs_to

Technical explanation: Consider a simple Rails application with two models: model A and model B. Model A is declared as ‘belongs_to’ model B when there exists a one-to-one connection that associates an instance of model A with model B.

English explanation: An example of a one-to-one relationship is that of a child to its biological mother. A child cannot biologically have more than one mother. Therefore, if the first model in your application is Child and the second model is Mother, each child is assigned or mapped to exactly one mother.

Example Code:

class Child < ApplicationRecord
belongs_to :mother
end
Source: giphy.com

has_many

Technical explanation: Consider a simple Rails application with two models: model A and model B. Model B ‘has_many’ instances of model A when there exists a one-to-many connection that associates an instance of model B with many instances of model A.

English explanation: An example of a one-to-many relationship is that of a mother to her children. A child cannot biologically have more than one mother but a mother can biologically have more than one child. Therefore, if the first model in your application is Child and the second model is Mother, each mother instance has many children instances associated with it.

Example Code:

class Mother < ApplicationRecord
has_many :children
end
Source: giphy.com