加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在我的灯具中加载HABTM与外键关系?

发布时间:2020-12-17 04:27:36 所属栏目:百科 来源:网络整理
导读:我有以下两个模型:School和User,以及它们之间的HABTM关系,带有连接表. 在此连接表中,引用User表的外键不是user_id,而是student_id. class School ActiveRecord::Base has_and_belongs_to_many :students,:class_name = "User",:join_table = "schools_stude
我有以下两个模型:School和User,以及它们之间的HABTM关系,带有连接表.

在此连接表中,引用User表的外键不是user_id,而是student_id.

class School < ActiveRecord::Base
 has_and_belongs_to_many :students,:class_name => "User",:join_table => "schools_students",:foreign_key => "student_id"
end

class User < ActiveRecord::Base
 has_and_belongs_to_many :studying_schools,:class_name => "School",:foreign_key => "school_id"
end

我想在我的用户和学校设备中创建一个学校和一个用户,但在User中定义的foreign_key似乎是个问题.

fixtures / users.yml:

user1:
  name: Student
  studying_schools: school1

fixtures / schools.yml:

school1:
  name: School 1
  active: true
  students: user1

加载上面的灯具会返回ActiveRecord异常:
ActiveRecord :: StatementInvalid:Mysql :: Error:’字段列表’中的未知列’user_id’:INSERT INTO schools_students(student_id,user_id)VALUES(6562055,14302562)

我究竟做错了什么 ?

解决方法

我刚刚发现它:我在habtm定义中缺少association_foreign_key.

正确的定义方法是:

class School < ActiveRecord::Base
 has_and_belongs_to_many :students,:association_foreign_key => "student_id"
 # :foreign_key is the default school_id
end

class User < ActiveRecord::Base
 has_and_belongs_to_many :studying_schools,:foreign_key => "student_id"
 # :association_foreign_key is the default school_id
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读