Rails db:migrate关系不存在

我有这样的模特:

学生:

class Student < ActiveRecord::Base has_many :participations, dependent: :destroy has_many :subject_item_notes, dependent: :destroy has_many :payments, dependent: :destroy has_many :subject_items, dependent: :destroy, through: :participations has_many :subject_items, dependent: :destroy validates :first_name, :last_name, presence: true accepts_nested_attributes_for :subject_items end 

和subject_item:

 class SubjectItem  (teacher) { where('teacher_id IS ? or teacher_id = ?', nil, teacher) } end 

和迁移:

 class AddStudentToSubjectItems < ActiveRecord::Migration def change add_reference :subject_items, :student, index: true end end 

但是当我做rake db:migrate

我收到错误:

 == 20151121045103 AddStudentToSubjectItems: migrating ========================= -- add_reference(:subject_items, :student, {:index=>true}) rake aborted! StandardError: An error has occurred, this and all later migrations canceled: PG::UndefinedTable: ERROR: relation "subject_items" does not exist : ALTER TABLE "subject_items" ADD "student_id" 

在恐慌中我多次重建数据库并且在架构中发生了一些混乱…… 🙁

至于现在我试着做:

rake db:drop然后rake db:create和rake db:migrate,然后出现此错误。

首先,检查您的迁移顺序。 在创建表subject_items本身之前,您似乎正在尝试创建引用。

您应首先创建学生表,然后创建您的subject_items表,然后添加参考。 或者在创建表时自己添加引用列,这就是add_reference所做的 。

此外,您有两个从StudentSubjectItem关系。

 has_many :subject_items, dependent: :destroy, through: :participations has_many :subject_items, dependent: :destroy 

您需要建立第一个关系,以便ActiveRecord能够首先识别正确的关系,然后进行查询以进行迁移。 想想如果你打电话给@student.subject_items就会生成的查询。 它会通过第一个关系还是第二个关系。

你的关系应该是ex:

 has_many :participation_subject_items, dependent: :destroy, through: :participations has_many :subject_items, dependent: :destroy