Reputation: 10214
So I have two models: User and ScheduledSession
The users have roles. One of the roles is "instructor".
ScheduledSession
belongs_to :instructor, :class_name => 'User', :foreign_key => 'instructor_id'
User
has_many :scheduled_sessions
GOOD! So I can do this...
s = ScheduledSession.first
s.instructor
BAD! But I can't do this...
u = User.first
u.scheduled_sessions
I get this error...
SQLite3::SQLException: no such column: scheduled_sessions.user_id: SELECT "scheduled_sessions".* FROM "scheduled_sessions" WHERE "scheduled_sessions"."user_id" = 1
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: scheduled_sessions.user_id: SELECT "scheduled_sessions".* FROM "scheduled_sessions" WHERE "scheduled_sessions"."user_id" = 1
How can I setup the relationship the other way around so I can see which scheduled sessions belongs to that instructor (user)?
Upvotes: 1
Views: 680
Reputation: 51697
You just need to set the foreign key in the User has_many relationship as well.
has_many :scheduled_sessions, :foreign_key => 'instructor_id'
Upvotes: 4