By: Category: Ruby on Rails,Web Development Technologies: Ruby on Rails
In Ruby on Rails, Active Record offers an interface among tables in a relational database. In MVC, Active Record is the M model. The Model interacts with the database, sends information to the controller, and is a SQL table. Association in Rails represents the relationship between models. It is also the association between two Active Record models.
To understand the relationship between models, it is important to determine the types of relationships. Whether it;
➢ Belongs_to
Belongs_to association is applied to show a reference to another one and describes which model includes a foreign key. Additionally, belongs_to associations use the singular term.
➢ Has_many
A has_many association is similar to a has_one association as it highlights a one-to-many connection with another model. The user can identify this association on the “other side” of a belongs_to association. This association symbolizes that each instance of the model has zero or more instances.
➢ Has_one
A has_one association signifies that one model has a reference to this model. That model can be obtained through this association.
For example, if the supplier in the application has one account, the user can declare the supplier model as resembled below:
class Supplier < ApplicationRecord
has_one:account
end
➢ Has_one:through
A has_many:through association is used to establish a many-to-many connection with another model. This association permits to match of the declaring model with zero or more instances of another model by progressing through a third model.
For example, in a medical practice where patients make appointments to see physicians. The relevant association declarations resemble the following:
➢ Has_and_belongs_to_many Association
Has_and_belongs_to_many association forms a direct many-to-many connection with other models. For the model to work, the user is required to use a join table. Join tables are formulated with a primary and foreign key of a relationship.
The naming convention of the join table includes the names of both models. It entails calling has_and _belongs_to_many for both models.
➢ Example: