Associations
In the previous chapter, we created a review web application where only authenticated users were allowed to write reviews. Ideally, every review would always allow other users to comment on it, and in this section, we will build that feature.
This means we will create a new model called Comment
, which will be associated with the Review
model since every review could have many comments, while every comment belongs to one review only. This is called a one-to-many relationship between the two models.
Associations are a set of methods for connecting objects of different models using foreign keys. Associations make it really simple to interact and perform various operations with records using Ruby code.
The following are six types of associations provided by Rails:
belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many
Let's discuss them one by one.
belongs_to
In the belongs_to
association...