Ruby on rails Rails关系未定义列
我有用户和缺席Ruby on rails Rails关系未定义列,ruby-on-rails,associations,model-associations,Ruby On Rails,Associations,Model Associations,我有用户和缺席 class User has_many :absences end class Absence belongs_to :student, foreign_key: "student_id", class_name: "User" end 我的缺席已经结束了 t.integer :student_id, index: true, null: false 出于某种原因,我可以说 Absence.first.student 但是当我说 Absence.first.st
class User
has_many :absences
end
class Absence
belongs_to :student, foreign_key: "student_id", class_name: "User"
end
我的缺席已经结束了
t.integer :student_id, index: true, null: false
出于某种原因,我可以说
Absence.first.student
但是当我说
Absence.first.student.absences
我明白了
ActiveRecord::StatementInvalid(PG::UndefinedColumn:错误:column
缺勤。用户id不存在)第1行:从中选择“缺勤”。*
“缺席”中的“缺席”。“用户”。。。
^:选择“缺勤”。*从“缺勤”中选择“缺勤”。“用户id”=$1限制$2
显然,我没有正确设置sth,因为它正在查找用户id而不是学生id,但我不知道为什么会发生这种情况…感谢您的任何建议!您之所以出现此错误,是因为您没有在has\u many relation中指定自定义外键。下面的代码将解决您的问题
class User
has_many :absences, foreign_key: "student_id"
end
class Absence
belongs_to :student, foreign_key: "student_id", class_name: "User"
end
出现此错误的原因是您没有在中指定自定义外键。以下代码将解决您的问题
class User
has_many :absences, foreign_key: "student_id"
end
class Absence
belongs_to :student, foreign_key: "student_id", class_name: "User"
end
我不知道我应该那样做…谢谢:)我不知道我应该那样做…谢谢:)