0

I have a question about has and belongs to many when it applies to multiple models. I've seen a couple other similar questions about habtm with multiple models but none quite like this (they usually apply to two models, not three).

Suppose I have The following classes:

  • Students
  • Clubs
  • Rooms

Students habtm Clubs--Students can join multiple Clubs and Clubs have multiple Students.

Rooms habtm Clubs--a Room may have multiple Clubs that use it and a Club may use multiple Rooms.

There is no direct relationship between Students and Rooms.

I don't see any issue with using two habtm relationships in the same class (the Club class), but there may be subtleties that I'm missing.

class Student < ActiveRecord::Base
  has_and_belongs_to_many :clubs
end

class Clubs < ActiveRecord::Base
  has_and_belongs_to_many :students
  has_and_belongs_to_many :rooms
end

class Rooms < ActiveRecord::Base
  has_and_belongs_to_many :clubs
end

I assume in such a case I can also use :through on one or both of the relationships.

  1. Are there any known issues?
  2. Is there some other pattern in Rails I should use instead that I'm not thinking of?
J.C. Yamokoski
  • 1,014
  • 9
  • 23
hershey
  • 465
  • 1
  • 8
  • 19
  • 1
    I don't think there is any issue at all with what you're doing. Having multiple (distinct) HABTM relationships in a single model is fine. – Chris Salzberg Aug 17 '12 at 22:18

1 Answers1

0

What you've posted is the correct and optimal design for this.

There's no similarities between room and student so a polymorphic isnt suitable and the relationships are right.

TomDunning
  • 4,829
  • 1
  • 26
  • 33