Zach
Zach

Reputation: 1243

Has Many Through in Rails 3

Ok so I'll try to make it quick. In my app, a user teaches many courses and a user takes many courses through => "enrollments".

User Model:
has_many :courses
has_many :courses, :through => :enrollments, :source => "course_id", :dependent => :destroy

Course Model:
belongs_to :user
has_many :users, :through => :enrollments, :source => "user_id", :dependent => :destroy

I set it all up according to standards and the has many through association works great. The problem is that when I am the teacher of the course and I try to delete it, or I try to call :

@courses = current_user.courses

I get this error:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError in CoursesController#destroy

I have a feeling that it's because I am calling both a regular has_many/belongs_to relationship even though I already have an existing has_many :through => :enrollments, and something is getting mixed up. I'm not sure how to get around this though. I would ideally like to create a method somewhere that gathers an array of the courses the user is teaching as well, something like current_user.teaching. Pretty lost, any help would be much appreciated.

Upvotes: 0

Views: 485

Answers (2)

Michael Durrant
Michael Durrant

Reputation: 96604

I would step back a little and start with what is perhaps a more classical hmt approch:

User Model:
has_many :enrollments
has_many :courses, :through => :enrollments, :dependent => :destroy
# id, other_fields, e.g. username

Enrollment Model:
belongs_to :user
belongs_to :course
# id, user_id, course_id, other fields, e.g. enrollment_date would be good...

Course Model:
has_many enrollments
has_many :users, :through => :enrollments, :dependent => :destroy
# id, other_fields, e.g. course_name

# `#` lists fields to create through database migrations (not shown).

current_user.courses might be ok now.

If you get an error make sure it is not about the method not existing for a nil object of course.

Upvotes: 1

Finbarr
Finbarr

Reputation: 32186

Change the declaration for the courses that the user teaches.

has_many :courses, :as => :taught_courses #or whatever you want

You may also want to change the declaration in course for clarity:

belongs_to :user, :as => :teacher

Upvotes: 0

Related Questions