Mike Bean
Mike Bean

Reputation: 65

Rails - both model are has_many

Sorry, I am not very advanced in mapping out databases

I have a model similar to this: A teacher can have many students, and a student can have many teachers. So How would I make this? If a student could have only one teacher I know I would set an attribute like: teacher_id: integer, then when I want to create a student it would be similar to this

Student.create(:teacher_id => id)

or query similar to this:

Student.where(teacher_id: id)
Teacher.find(student.teacher_id)

But I am unsure of how to accomplish this if both are has_many relationships

Upvotes: 0

Views: 297

Answers (3)

anusha
anusha

Reputation: 2135

You can use rails has_and_belongs_to_many relationship for your requirement. check this link for reference: http://guides.rubyonrails.org/association_basics.html#has-and-belongs-to-many-association-reference

you need to use this relationship like this:

teacher.rb

has_and_belongs_to_many :students

student.rb

has_and_belongs_to_many :teachers

then you need to add a migration to create a join table containing teacher_id and student_id

you should create name of your migration in alphabetical order like this:

rails g migration create_join_table_for_students_teachers student_id:integer teacher_id:integer

and then rake db:migrate

then you can access students of a single teacher like teacher.students etc.,

Hope this might help you in some way please go through the reference link once

Upvotes: 1

ilyabyar
ilyabyar

Reputation: 5

Better use has_many:through relation.

Upvotes: 0

Jordan Running
Jordan Running

Reputation: 106077

You're describing a has-and-belongs-to-many (HABTM) relation, which Rails supports in two ways: has_and_belongs_to_many or has_many :through. You can read about them in the Active Record Associations Rails Guide, which also gives you tips and how to choose which one is appropriate for your application.

Upvotes: 0

Related Questions