Reputation: 1047
Is it possible to define the following relationship:
I know how to do it with one more table(adding a student_course table which holds the id of the student and the course it belongs to and then saying that the a student has_many :courses, through: :student_course).
In other words, could it be implemented just by editing the following tables?
class Student
belongs_to :group
end
class Group
has_many :students
has_many :courses
end
class Course
belongs_to :group
end
Upvotes: 1
Views: 58
Reputation: 168081
Not sure if you can do it with a Rails class method, but you can just implement it manually.
class Student
belongs_to :group
def courses
group.courses
end
end
class Group
has_many :students
has_many :courses
end
class Course
belongs_to :group
end
Upvotes: 2
Reputation: 7361
Try below associaion
student.rb
belongs_to :group
has_many :courses, through: :group
group.rb
has many :courses
has many :students
course.rb
belongs_to :group
has_many :students, through: :group
Upvotes: 2