0

My Seminar model has a column named teacher_id. That part of the relationship is working. I can call seminar.teacher to retrieve the User who teaches that seminar.

I'd like to be able to invert that query. In other words, I need to call teacher.own_seminars to get a collection of all the seminars where that User is listed as the teacher_id. I know that I could call Seminar.where(:teacher => teacher), but that's clunky. And I think that the performance is probably worse that way.

Note: Some of the Users are students who are linked to Seminar through the seminar_user join table, but I don't think that affects this question.

This is the model setup that isn't quite working yet

class User < ApplicationRecord
    has_many     :own_seminars, :class_name => "Seminar", foreign_key: 'own_seminar_ids'
end



class Seminar < ApplicationRecord
    belongs_to  :teacher, class_name: "User", foreign_key: 'teacher_id'
end

Cheers!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Jeff Zivkovic
  • 547
  • 1
  • 4
  • 20

1 Answers1

2

In foreign_key option, you specify the column which is, well, the foreign key.

The way has_many works, is it tries to guess, which one of the fields in the referenced entity corresponds to the primary key of this entity. By default, it's user_id (derived from name User). But since your column is actually called teacher_id, you should use that instead.

has_many :own_seminars, 
         class_name: "Seminar", 
         foreign_key: 'teacher_id'
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367