Search code examples
ruby-on-railsassociationsrails-activerecordclass-names

Get association from custom name


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!


Solution

  • 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'