HABTM, or multiple belongs_to?
Asked Answered
L

2

7

I'm teaching myself Rails, and as a test project I'm mocking up a simple question/answer app similar to stackoverflow.

In my simplified version I have:

  • questions
  • answers
  • users (the authors of questions and answers)
I get that answers belong to questions.
  • What's the proper relationship between users and questions?
  • What's the proper relationship between users and answers?

It would seem to me that questions and answers don't really "belong_to" users, and instead questions and answers "has_one user" (the author). But that doesn't seem right either, because then the user would "belong_to question" and "belong_to answer".

Is HABTM the answer between the three classes?

Lots of people get stuck on this relationship thing, don't they? :)

Lashio answered 13/1, 2010 at 5:52 Comment(0)
C
7

Is HABTM the answer between the three classes?

No. You don't need HABTM in any of these relationships.

  • What's the proper relationship between users and questions?
  • What's the proper relationship between users and answers?

In both of these cases, it is a one-to-many relationship: A user has many questions and a user has many answers.

From a logical point of view, consider this: One question can never be authored by multiple users and one answer cannot be authored by multiple users. As such, it's not a many-to-many relationship.

In this case, your classes should be set up like this:

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 tagging system similar to StackOverflow, you'll need a HABTM relationship. One question can have many tags, while one tag can have many questions. As a prime example, your post has three tags (ruby-on-rails, habtm, foreign-key-relationship), while the ruby-on-rails tag presently have 8,546 questions.

Carroty answered 13/1, 2010 at 6:34 Comment(0)
S
0

Belongs_to is a strange name. Figure out your has_many relationships and just put belongs_to on the other side and don't worry about the semantics of it.

Supermundane answered 13/1, 2010 at 5:55 Comment(1)
whoops - yeah didn't mean "belongs_to". So, I'm getting way too caught up in the meaning of the words in English, vs the meaning of the words in Rails.Lashio

© 2022 - 2024 — McMap. All rights reserved.