如何在我的灯具中加载HABTM与外键关系?

时间:2009-09-25 02:04:56

标签: ruby-on-rails foreign-keys fixtures has-and-belongs-to-many

我有以下两个模型: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", :join_table => "schools_students", :foreign_key => "school_id"
end

我想在我的用户和学校设备中创建学校和用户,但用户中定义的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: Unknown column 'user_id' in 'field list': INSERT INTO schools_students (student_id, user_id) VALUES (6562055, 14302562)

我做错了什么?

1 个答案:

答案 0 :(得分:18)

我刚刚发现:我错过了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 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