新手问题 多对多关联出现 Could not find the source association (s) 错误

akayuki · 2017年05月08日 · 最后由 chalvern 回复于 2017年05月09日 · 2370 次阅读

在做一个学生作业系统的时候出现的问题,Student 通过 Enrollment 与 Course 多对多关联,先上代码

class Course < ApplicationRecord
    has_many   :enrollments
    has_many   :students, :through => :enrollments, :source => :user, :conditions => { :type => 'Student' }
end

class Student < User
    has_many   :enrollments
    has_many   :courses, :through => :enrollments, :source => :course
end

class Enrollment < ApplicationRecord
    belongs_to :course
    belongs_to :student
end

在 rails console 里执行 student.courses 的时候系统提示 ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :course in model Enrollment. Try 'has_many :courses, :through => :enrollments, :source => <name>'. Is it one of ?

Student 这个 model 是从 User 单表继承过来的,source 那里应该填 user 还是 student?两种都试了下但是一样会出错,能麻烦各位帮忙看一下吗?

把 Course 代码改成之后就好了:

class Course < ApplicationRecord
    belongs_to :teacher
    has_many   :enrollments
    has_many   :students, :through => :enrollments
end

然而这时我最开始出错时候的代码,不知道发生了什么。。

has_many 第一个参数会默认设置很多东西。。。。

我的理解是,你在 has_many: students 的时候,已经默认 source 是 student 了,但是你却又指定了它的 source 是 user,这里面有一个转换是走不通的

需要 登录 后方可回复, 如果你还没有账号请 注册新账号