7

我有以下两个模型: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)

我究竟做错了什么 ?

4

1 回答 1

21

我刚刚发现:我association_foreign_key在 habtm 定义中遗漏了 。

定义它的正确方法是:

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
于 2009-09-25T02:59:57.260 回答