كيف يمكنني تحميل العلاقات الرئيسية مع Habtm-with-beporty في صميمي؟
-
16-09-2019 - |
سؤال
لدي النموذجان التاليان: المدرسة والمستخدم، وعلاقة Habtm بينهما، مع جدول الانضمام.
في جدول الانضمام هذا، لا يسمى المفتاح الأجنبي الذي يشير إلى جدول المستخدم 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
أرغب في إنشاؤه في المستخدمين والمدارس الخاصة بي لمدرسة ومستخدم، ولكن يبدو أن Movie_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)
ما الخطأ الذي افعله ؟
المحلول
أنا فقط وجدت ذلك: كنت في عداد المفقودين association_foreign_key
في تعريف habtm.
الطريقة الصحيحة لتحديدها هي:
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
لا تنتمي إلى StackOverflow