visit
Understanding associations is vital to create a web application that behaves as you expect and avoid a good dose of frustration. In Rails, an association is a connection between two Active Record models.
Rails supports six types of associations:
belongs_to: Specific for relationships of type one-to-one (1: 1) with another model (class). This method can be used only if this class contains the foreign key. If the other class contains the foreign key must use
has_one
instead.class DoctorOffice < ApplicationRecord
belongs_to :doctor
end
has_one: Specific for relationships of type one-to-one (1: 1) with another model. This method can be used only if the other class contains the foreign key. If the current class contains the foreign key must use
belongs_to
instead.class Doctor < ApplicationRecord
has_one :doctor_office
end
has_many: Specify an association of one to many (1: N). The referenced model must implement
belongs_to
.class Doctor < ApplicationRecord
has_many :patients
end
has_many :trough: Specify an association of many to many (N: M) with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.
class Doctor < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :doctor
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :doctors, through: :appointments
end
has_one :trough: Specify an association of one to one (1: 1) with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding through a third model.
class Patient < ApplicationRecord
has_one :account
has_one :account_history, through: :account
end
class Account < ApplicationRecord
belongs_to :patient
has_one :account_history
end
class AccountHistory < ApplicationRecord
belongs_to :account
end
has_and_belong_to_many: Specify a direct association of many to many (N: M) with another model, with no intervening model.
class Doctor < ApplicationRecord
has_and_belongs_to_many :patients
end
class Patient < ApplicationRecord
has_and_belongs_to_many :doctors
end