5

我有以下兩種模型:School和User,以及它們之間的HABTM關係,並帶有一個連接表。如何在我的燈具中加載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)

我在做什麼錯?

回答

15

我剛剛發現它:我錯過了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