2012-04-27 77 views
1

所以我有兩個模型:User和ScheduledSessionRails 3. has_many as other class

用戶有角色。其中一個角色是「講師」。

ScheduledSession 
belongs_to :instructor, :class_name => 'User', :foreign_key => 'instructor_id' 

User 
has_many :scheduled_sessions 

好!所以我可以這樣做...

s = ScheduledSession.first 
s.instructor 

不好!但是,我怎麼能建立關係的其他方式,所以我可以看到哪些預定會議屬於我不能做到這一點...

u = User.first 
u.scheduled_sessions 

我得到這個錯誤...

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 

那位教練(用戶)?

回答

4

您只需在用戶has_many關係中設置外鍵即可。

has_many :scheduled_sessions, :foreign_key => 'instructor_id' 
+0

太簡單了,太棒了!謝謝。 (它之前只需要一個逗號:foreign_key) – leonel 2012-04-27 22:55:08

+0

我修正了它,以防其他人遇到。 – 2012-04-27 22:58:23