An intermediate table that connects two tables

What is an intermediate table?

A convenient guy who takes charge of the table when there is a "many-to-many" relationship between the two tables you want to associate with.

Concrete example

When you think of LINE, one user belongs to several groups. Also, many users are invited to one group. At this time, it can be said that the user and the group have a "many-to-many" relationship.

problem

It is difficult to associate a "many-to-many" table as it is.

solution

In the previous example, we would have a table between the user and the group to record the combination. That is the intermediate table. The point is to record the combination of user and group, and the column needs the user id and group id.

Description

Use "has_many method" and "belongs_to method" to make an association. From the perspective of the model (table) file, consider whether there are multiple or singular models (tables) that you want to have a connection with. ex) user (model) has_many groups This is no longer an English story.

group.rb


has_many :user_groups
has_many :users, through: :user_groups

user.rb


has_many :user_groups
has_many :groups, through: :user_groups

user_group.rb


belongs_to :user
belongs_to :group

Caution

Use the "through option" for models that are not directly connected.

point

-[x] The intermediate table is always "belongs_to method", and the model name that follows is singular. -[x] The tables you want to associate with each other indirectly have a many-to-many relationship. -[x] Tables that are not intermediate tables are always "has_many method", and the model name that follows is plural. -[x] Use the "through option" to describe the model name you are passing through in plural form.

Finally

I will post to Qiita for the first time in my life. It is intended for your own output, but if you notice anything, please point it out.

Recommended Posts

An intermediate table that connects two tables