Skip to content

Instantly share code, notes, and snippets.

@daveroberts
Created June 6, 2014 19:09
Show Gist options
  • Save daveroberts/f0d8a1559e9bd01c0052 to your computer and use it in GitHub Desktop.
Save daveroberts/f0d8a1559e9bd01c0052 to your computer and use it in GitHub Desktop.
class Klass < ActiveRecord::Base
has_one :teacher
has_many :students
end
class Teacher < ActiveRecord::Base
belongs_to :klass
has_many :students, through: :klass
end
class Student < ActiveRecord::Base
belongs_to :klass
has_one :teacher, through: :klass
end
k1 = Klass.create(name: "Room 1")
k2 = Klass.create(name: "Room 1")
s1 = Student.create(name: "Abbey", klass: k1)
s2 = Student.create(name: "Brooke", klass: k1)
s3 = Student.create(name: "Courtenay", klass: k2)
t1 = Teacher.create(name: "Miss Jane", klass: k1)
t2 = Teacher.create(name: "Miss Martha", klass: k2)
Klass.first.name
# "Room 1"
Klass.first.teacher.name
# "Miss Jane"
Klass.first.students.first.name
# "Abby"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment