Association (one-to-many relationship)

Association (one-to-many relationship)

1. 1. What is an association?

To put it simply, it means "associate each model with each other." In other words, the tables are associated with each other so that ** one model can access the other **.

Example. ** A pattern in which one user owns multiple comments (one-to-many relationship) ** aso0.png → Connect "** A-san " with A-san's comments " Good morning " and " Good evening **". → is "Mr. ** B " and B's comment " Hello ", linking the " goodbye **".

2. has_many and belongs_to methods

Now let's show how to reproduce the association in code. Consider the above ** pattern in which one user owns multiple comments (one-to-many relationship) **. (1) has_many aso01.png

#User model
class User < ApplicationRecord
 has_many :comments       #Since one user owns multiple comments, it becomes a plural comment.
end

(2) belongs_to aso02.png

#Comment model
class Comment < ApplicationRecord
 belongs_to :user      #One comment is owned by one user, so it is a singular user.
end

3. 3. finally

I explained the basic idea of one-to-many associations. In the future, I would like to continue to post a little more applied things such as many-to-many relationships. Also,. If you have any mistakes, please comment!

Recommended Posts

Association (one-to-many relationship)
Association (one-to-many)! !!
One-to-many relationship
Association (many-to-many)! !!
Rails association gives one-to-many relationships between models
Association (1 to 1)! !!