所以我有两个模型:User 和 ScheduledSession
用户有角色。其中一个角色是“指导员”。
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
我如何设置相反的关系,以便我可以看到哪些已安排的类(class)属于该讲师(用户)?
最佳答案
你只需要在 User has_many 关系中设置外键。
has_many :scheduled_sessions, :foreign_key => 'instructor_id'
关于ruby-on-rails - Rails 3. has_many 作为另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358855/