How can I load HABTM-with-foreign-key relationships in my fixtures?

Julien picture Julien · Sep 25, 2009 · Viewed 7k times · Source

I have the following two models: School and User, and a HABTM relationship between them, with a join table.

In this join table, the foreign key refering to the User table is not called user_id but 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

I would like to create in my Users and Schools fixtures a school and a user, but the foreign_key defined in User seems to be a problem.

fixtures/users.yml :

user1:
  name: Student
  studying_schools: school1

fixtures/schools.yml :

school1:
  name: School 1
  active: true
  students: user1

Loading the fixtures above returns an ActiveRecord exception : ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'user_id' in 'field list': INSERT INTO schools_students (student_id, user_id) VALUES (6562055, 14302562)

What am I doing wrong ?

Answer

Julien picture Julien · Sep 25, 2009

I just found it out : I was missing the association_foreign_key in the habtm definition.

The correct way to define it is :

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