【问题标题】:Rails relationship undefined columnRails 关系未定义列
【发布时间】:2018-06-22 09:21:59
【问题描述】:

我有用户和缺席

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: ERROR: column 缺席.user_id 不存在)第 1 行:选择“缺席”。* FROM “缺席” WHERE “缺席”。“user_... ^ : SELECT "absences".* FROM "absences" WHERE "absences"."user_id" = $1 LIMIT $2

显然,我没有正确设置某事,因为它正在寻找 user_id 而不是 student_id 但我不知道为什么会发生这种情况...谢谢您的任何建议!

【问题讨论】:

    标签: ruby-on-rails associations model-associations


    【解决方案1】:

    您收到此错误的原因是您没有在 has_many 关系中指定自定义外键。以下代码将解决您的问题。

    class User
      has_many :absences, foreign_key: "student_id"
    end
    
    class Absence 
      belongs_to :student, foreign_key: "student_id", class_name: "User"
    end
    

    【讨论】:

    • 我不知道我应该这样做...谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多