7

次の 2 つのモデルがあります。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_keyhabtm 定義に がありませんでした。

それを定義する正しい方法は次のとおりです。

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 に答える