Active Record Associations in Rails: Beginners Guide
As Ruby on Rails developers, we do not have to worry too much about the operations in the database due to the Object-Relational-Mapping or ORM. The ORM allows us to focus more on the logic of the business while it handles the operations with the database on our behalf.
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.
Let’s imagine we have a client asking us to build a hospital management web app. Depending on the hospital needs we would need to create some Active Record Models.
Now let’s take a couple of these models as an example: one for the doctors and one for the patients. We need to tell Rails that a doctor has many patients and one patient might have one or more doctors, we achieve these trough associations.
Rails supports six types of associations:
class DoctorOffice < ApplicationRecord belongs_to :doctor end
class Doctor < ApplicationRecord has_one :doctor_office end
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
If you are new to Rails associations or Rails, in general, I hope this quick introduction contributed to clarify some of your doubts about this topic.