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

一曲冷凌霜 提交于 2019-12-04 22:33:26

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/1475088/how-can-i-load-habtm-with-foreign-key-relationships-in-my-fixtures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!