・ Relationship between models in which multiple columns are linked to each other ・ Example): The relationship between the board of the bulletin board application and the tag (posts with different posts but similar tags have a many-to-many relationship)
・ Prepare an intermediate table (defined as model (middle) in the explanation in this post) -The intermediate table has a simple structure with only [: id, many 1_id, many 2_id]
rails g <model(Many)1> <column information>
rails g <model(Many)2> <column information>
rails g model <model(During ~)> <model(Many)1>:references <model(Many)2>:references
-Intermediate tables are usually named "model (many) 1_model (many) 2_relations" ・ Model names are all lowercase and singular.
rails db:migrate
・ The model set in ①② is reflected in the table of db
model(During ~).rb
class model(During ~) < ApplicationRecord
belongs_to :model(Many)1
belongs_to :model(Many)2
end
・ This description is automatically written at the time of generate ・ Since two belongs_to have already been set, no touch is required.
model(Many)1.rb
class model(Many)1 < ApplicationRecord
has_many :<model(During ~)s>
has_many :<model(Many)2s>, through: :<model(During ~)s>
end
・ Through :: <model (middle) s>
means that it goes through model (middle) between two models.
・ (Meaning model (many) 1 → model (medium) → model (many) 2)
・ It is necessary to describe here that it goes through the intermediate table.
・ Model name is described in plural form
model(Many)2.rb
class model(Many)2 < ApplicationRecord
has_many :<model(During ~)s>
has_many :<model(Many)1s>, through: :<model(During ~)s>
end
・ Set two has_many as in model (many) 1. ・ Model name is described in plural form
Recommended Posts