困惑铁轨活动记录关联

时间:2014-01-01 13:39:11

标签: ruby-on-rails activerecord model-associations

4模型在其表格中有以下列

student : student_id  name    dept
semester: semester_id semester_name
subject : subject_id  subject_name  semester_id
result  : student_id  semester_id   result_id result

我已将模型关联为

student: has_many semesters
         has_many subjects through semesters
         has_many results through semesters

semester: belongs_to students
          has_many subjects
          has_many results

subject: belongs_to semesters
         has_many student through semesters

result: has_many students through semesters
        belongs_to semesters

如果可以,请告诉我。我很困惑何时使用belongs_to。我的意思是,我可以使用下面的东西吗?

student: has_many semesters
         has_many subjects through semesters            

semester: has_many students
          has_many subjects              

subject: has_many semesters
         has_many student through semesters 

2 个答案:

答案 0 :(得分:0)

正确的方法是:

Student: has_many :semesters
         has_many :subjects, through: semesters            

Semester: belongs_to :student
          belongs_to :subject              

Subject: has_many :semesters
         has_many :students, through: :semesters 

您需要进行以下迁移:

drop_table :results # you won't need it anymore if you use has_many through
remove_column :students, :student_id, :integer
add_column :students, :id, :integer # if you don't have the ID column in your students table
remove_column :subjects, :subject_id, :integer
add_column :subjects, :id, :integer
add_reference :semesters, :student, index: true
add_reference :semesters, :subject, index: true

答案 1 :(得分:0)

该类具有belongs_to定义始终是具有外键声明的对应db表。