Efrain Tlapale Efrain Tlapale - 1 year ago 96
Ruby Question

Relations Between 3 models in rails (Teacher,Subject,Student)

I need help to structure the relations between 3 models in rails
Teacher, Subject and Student

I don't know if it is possible, but I hope so

a students can be in multiple subjects, and he belong to a teacher

a subject can have multiple students and it belongs to a teacher

Teachers may be able to add subjects and to acces all students

Answer Source

H Efrain,

You want to learn Ruby on Rails Associations (http://guides.rubyonrails.org/association_basics.html).

There are:

  1. has_many
  2. has_one

Now in your particular case you need make your:

class Subject < ActiveRecord::Base
  has_many :students
  belongs_to :teacher

class Student < ActiveRecord::Base
  belongs_to :teacher
  has_many :subjects

class Teacher < ActiveRecord::Base
  has_many :students
  has_many :subjects

You also need to create certain migrations

You migrations need to have references as well! http://edgeguides.rubyonrails.org/active_record_migrations.html

There is good rails g migration approach lets you add references to existing model:

$ bin/rails generate migration AddStudentRefToSubjects student:references

what returns:

class AddStudentRefToSubjects < ActiveRecord::Migration
  def change
    add_reference :subjects, :student, index: true, foreign_key: true

Finally you can access your instances through (example)

Subject.last.students // returns all students for last subject in your DB
Teacher.last.students // returns all students for last teacher in your DB
Subject.last.teacher // returns teacher instance of last subject
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download