What does a join table mean?

2

I was reading the book Beginning Rails 4, when I came across messe excerpt on page 100.

  

Let's get back to the relationship between users and comments. You need to tell your user that you have many comments through its articles. Basically, you use the article model as a join table between users and comments. You achieve the link using the has_many: through method.

What does this join table concept mean? I understood in the code what it does, but I wanted a more formal concept for it.

    
asked by anonymous 04.09.2014 / 14:09

1 answer

3

I imagine the templates should look something like this:

User:
  id
  username

Article:
  id
  user_id
  title
  text

Comment:
  id
  article_id
  text

So a user has a lot of comments pertaining to their questions, only this happens articles .

In the following statement you inform this to Rails:

class User
  has_many :articles
  has_many :comments, through: :articles
end

Imagine that you have an object @user of id 99 . When you use @user.articles it will generate a SQL like this:

SELECT *
FROM articles
WHERE user_id = 99

There was no need for JOIN.

But if you do @user.comments it will have to do a JOIN:

SELECT comments.*
FROM comments
INNER JOIN articles
  ON comments.article_id = articles.id
WHERE articles.user_id = 99

Now imagine that a comment might have many answers:

class User
  has_many :articles
  has_many :comments, through: :articles
  has_many :replies, through: :comments
end

When doing @user.replies it will do two JOINs:

SELECT replies.*
FROM replies
INNER JOIN comments
  ON replies.comment_id = comments.id
INNER JOIN articles
  ON comments.article_id = articles.id
WHERE articles.user_id = 99

Conclusion

So, "join table" is when this indirect relationship exists between tables.

    
04.09.2014 / 14:40