Kyle Sletten
Kyle Sletten

Reputation: 5413

Multiple levels of have_many in a model

I am working with Ruby on Rails (specifically the ActiveRecord) and I am trying to decide whether or not it is a good idea to link my models using multiple levels.

class Student < ActiveRecord::Base
  has_many :student_sections
  has_many :sections, :through => :student_sections
  has_many :courses, :through => :sections
end

It seems like this would work, but I don't have a lot of experience in ActiveRecord. Is there any reason not to do this?

Upvotes: 0

Views: 161

Answers (2)

Max Williams
Max Williams

Reputation: 32933

This is fine but you should bear in mind that the courses association is effectively only a 'get' association (as opposed to 'get and set'). What i mean by that is that you can say

@student.courses

(after doing neo's fix) to get a list of courses, but you can't do

@student.courses << @course

as rails doesn't have the section info required to make the necessary joins between the student and the course.

Upvotes: 2

Neo
Neo

Reputation: 5463

you need to add :source attribute

has_many :sections, :through => :student_sections, :source => 'your_source'

Upvotes: 0

Related Questions