Association in Ruby on Rails

Association in Ruby on Rails

30 Nov 2021
0 Comments
Association in 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

  • Has_many

  • Has_one

  • Has_one:through

  • Has_and_belongs_to_many

 

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.

belongs-to-association

 

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.

 

For example, for applications with authors and books, the author model is declared like the following:

class Author < ApplicationRecord

has_many:books

end

Has-many-association

 

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-association

 

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 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-one-through-association

 

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.

has-and-belongs-to-many-association

The naming convention of the join table includes the names of both models. It entails calling has_and _belongs_to_many for both the models.

 

 Example:

association-example

 

association-example-list




Leave a comment: