Today I would like to implement a many-to-many table implementation in Rails.

First model

th_words andstudiesIs a many-to-many relationship. There are also intermediate tables

This time, jp_words is related to th_words as a child table.
I would like to display until then.

Many-to-many association

Write this on the model.

Study Model

class StudyThWord < ApplicationRecord
  belongs_to :th_word
  belongs_to :study


Next th_words Model

 has_many :study_th_words
 has_many :studies, through: :study_th_words


Next, the intermediate table study_th_words

class StudyThWord < ApplicationRecord
  belongs_to :th_word
  belongs_to :study


The model is OK now.
The rest is written on the controller.
But before that, you have to think about how you want to display it in View.

Check Screen

This lesson page is a study page, and many Thai languages are associated with it.
Then, controller is described based on this

  def show
   # @ sudy, get your current id and put in
    @study = Study.find(params[:id])
  # @ words is packed with many-to-many relationships with the study. You can get a lot, so keep it in plural.
    @words = @study.th_words


I wrote everything on show. To be easy to understand
Left off before_action: set_study,
This show method is all.

All you have to do is write in View based on this.


# @ words contains a lot of th_words, so we ’ll turn it around. Loop as many times as you have stored in the array. Use th_word in the loop.
<% @words.each do |th_word| %>
#This is just underlined on the screen. Don't think too much.

# tag.div just wears a div tag. Do n’t worry. The next important thing is that th_word is a table of th_words, and the word in that column is displayed. {The following are just css guesses. <%= tag.div th_word.word, {class: "col-md-4", style: "font-size: 1.62rem; "} %> #This line displays the phonetic symbols in the th_words table <%= tag.div th_word.pronounce, {class: "col-md-4", style: "font-size: 1.62rem;"} %> #From here you will see the jp_words associated with the associated th_word. But jp_word is an array, so you have to consider it So again, we'll turn the loop on use each <% th_word.jp_words.each do |jp_word| %> <%= tag.div jp_word.word, {class: "col-md-4", style: "font-size: 1.5rem;"} %> <% end %>
<% end %>


Is this all right.
I tried to explain the many-to-many association of Rails.

The order is first
1. Model relations
2. Pack into the controller. It ’s time to imagine how you want to use it in View.
3. Write to View. This only shows what is packed into the instance variables.
Is a controller more important?
And today th_word had a child table, so it looped again. Otherwise you will not see an error.

So we have successfully implemented a many-to-many table of rails.
If you have any questions, please comment below.
If there is a mistake, please let me know.

It was happy end.