Kristiyan Tsvetanov
Kristiyan Tsvetanov

Reputation: 1047

Rails - model relationship suggestion

Is it possible to define the following relationship:

  1. A 'student' belongs to a 'group'
  2. A 'group' has many 'courses' and many 'students'
  3. A 'student' has many 'courses' through the 'group' it belongs to

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

Answers (2)

sawa
sawa

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

Vishal
Vishal

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

Related Questions