Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails关系未定义列_Ruby On Rails_Associations_Model Associations - Fatal编程技术网

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

我不知道我应该那样做…谢谢:)我不知道我应该那样做…谢谢:)