0

I have the models Student, Classroom and Course. I have a has_and_belongs_to_many association between Student and Classroom, and another has_and_belongs_to_many association between Classroom and Course.

I have already Created the models and the databases are populated.

Now, how do I add a has_many association between Student and Course and one between Course and Student?

Thanks!

user1175969
  • 540
  • 6
  • 19
  • http://stackoverflow.com/a/11601236/1301840 – lusketeer Jun 21 '16 at 09:53
  • Just write an association in the model as you normally would, but if the association name differs from the model name you are associating with then be sure to specify the class_name too as well as any foreign key linking the two tables. – hypern Jun 21 '16 at 09:55
  • What i think is, you have to make `classroom` as middle(junction or through) Table and make `has_many` association for both `student` and `course` with `classroom` Table. And, further you can establish relationship between `student` and `course` `through classroom` – Pravesh Khatri Jun 21 '16 at 09:55

1 Answers1

0

You should maintain

has_many through association

rather than maintaining relation between student classroom, then classroom course and student course. Try something like this:

In student.rb
has_many :classrooms
has_many :courses, through: :classrooms

In course.rb
has_many :classrooms
has_many :students, through: :classrooms

In classroom.rb
belongs_to :student
belongs_to :course
SnehaT
  • 309
  • 4
  • 14