如何在我的灯具中加载HABTM与外键的关系? [英] How can I load HABTM-with-foreign-key relationships in my fixtures?
问题描述
在这个连接表中,引用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
结束
class用户< ActiveRecord :: Base
has_and_belongs_to_many:studying_schools,:class_name => School,:join_table => schools_students,:foreign_key => school_id
end
我想在我的用户和学校设备中创建一所学校和一个用户,但在用户定义foreign_key似乎是一个问题。
fixtures / users.yml
:
user1:
名称:Student
studying_schools:school1
fixtures / schools.yml
:
school1:
$加载上述装置返回一个ActiveRecord异常:
name:School 1
active:true
students:user1
ActiveRecord :: StatementInvalid:Mysql :: Error:未知列'user_id'in 'field list':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,:class_name => User,:join_table => schools_students,:association_foreign_key => student_id
#:foreign_key是默认的school_id
结尾
class用户< ActiveRecord :: Base
has_and_belongs_to_many:studying_schools,:class_name => School,:join_table => schools_students,:foreign_key => student_id
#:association_foreign_key是默认的school_id
end
I have the following two models: School and User, and a HABTM relationship between them, with a join table.
In this join table, the foreign key refering to the User table is not called
user_id
butstudent_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", :join_table => "schools_students", :foreign_key => "school_id" end
I would like to create in my Users and Schools fixtures a school and a user, but the foreign_key defined in User seems to be a problem.
fixtures/users.yml
:user1: name: Student studying_schools: school1
fixtures/schools.yml
:school1: name: School 1 active: true students: user1
Loading the fixtures above returns an ActiveRecord exception :
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'user_id' in 'field list': INSERT INTO schools_students (student_id, user_id) VALUES (6562055, 14302562)
What am I doing wrong ?
解决方案I just found it out : I was missing the
association_foreign_key
in the habtm definition.The correct way to define it is :
class School < ActiveRecord::Base has_and_belongs_to_many :students, :class_name => "User", :join_table => "schools_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, :class_name => "School", :join_table => "schools_students", :foreign_key => "student_id" # :association_foreign_key is the default school_id end
这篇关于如何在我的灯具中加载HABTM与外键的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!