5

Mam następujące dwa modele: Szkoła i Użytkownik oraz relacji HABTM między nimi, z tabelą dołączenia.Jak mogę załadować relacje HABTM-z-kluczem obcym w moich urządzeniach?

W tej tabeli łączenia klucz obcy odnoszący się do tabeli użytkowników nie jest nazywany user_id, ale 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 

Chciałbym stworzyć w moich użytkowników i szkół opraw szkoły i użytkownika, ale foreign_key zdefiniowany w Użytkownik wydaje się być problemem.

fixtures/users.yml:

user1: 
    name: Student 
    studying_schools: school1 

fixtures/schools.yml:

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

Ładowanie urządzeń powyżej zwraca wyjątek ActiveRecord: ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'user_id' in 'field list': INSERT INTO schools_students (student_id, user_id) VALUES (6562055, 14302562)

Co robię źle?

Odpowiedz

15

Właśnie się dowiedziałem: brakowało mi association_foreign_key w definicji habtmu.

Prawidłowy sposób go zdefiniować to:

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 
Powiązane problemy