HABTM or more belongs to_to?

I teach Rails, and as a test project, I mock a simple question / answer similar to stackoverflow.

In my simplified version, I have:

  • the questions
  • the answers
  • users (question and answer authors)
I get the answers to belong to the questions.
  • What is the correct connection between users and questions?
  • What is the correct relationship between users and answers?

It seems to me that the questions and answers do not really "belong" to users, but instead the questions and answers have "has_one user" (author). But this also does not seem to be correct, because then the user will "belong to the question" and "belong" to answer. "

Is HABTM the answer between the three classes?

A lot of people get stuck in this regard, right? :)

+7
ruby-on-rails foreign-key-relationship has-and-belongs-to-many
source share
2 answers

Is HABTM the answer between the three classes?

Not. You do not need HABTM in any of these relationships.

  • What is the correct connection between users and questions?
  • What is the correct relationship between users and answers?

In both cases, this is a one-to-many relationship: the user has many questions, and the user has many answers.

From a logical point of view, consider this: One question can never be authorized by several users, and one answer cannot be authorized by several users. . As such, this is not a many-to-many relationship.

In this case, your classes should be configured as follows:

class User < ActiveRecord::Base has_many :questions has_many :answers end class Question < ActiveRecord::Base belongs_to :user has_many :answers end class Answer < ActiveRecord::Base belongs_to :user belongs_to :question end 

If you, on the other hand, have a tag system similar to StackOverflow, you need a HABTM relationship. One question can have many tags, while one tag can have many questions. As a basic example, your post has three tags (ruby-on-rails, habtm, external relations), while the ruby-on-rails tag has 8,546 questions.

+7
source share

Belongs_to is a strange name. Explain your has_many relationship and just put your own_to on the other hand and don't worry about the semantics of this.

0
source share

All Articles