5

私は以下の2つのモデルを持っています:学校とユーザー、そしてそれらの間の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 
関連する問題