What does a "Join table" mean?

Asked

Viewed 302 times

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 model that a user has Many comments through its Articles. Basically, you use the article model as a Join table between users and comments. You Achieve the linking using the has_many :through method.

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

  • Do you know if the excerpt refers to the use of join table in an SGBD?

1 answer

3

I imagine the models must be something like this:

User:
  id
  username

Article:
  id
  user_id
  title
  text

Comment:
  id
  article_id
  text

So a user has many comments pertaining to their questions, only this happens across table Articles.

In the following statement you inform this to the Rails:

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

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

SELECT *
FROM articles
WHERE user_id = 99

No need for JOIN.

But if you do @user.comments he 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 can have many answers (Replies):

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

In doing @user.replies he’ll 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

Completion

Therefore, "Join table" is when there is this indirect relationship between tables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.