Rails db:migrate 关系不存在

Rails db:migrate relation does not exist

我有这样的模型:

学生:

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 < ActiveRecord::Base
  has_many :participations, dependent: :destroy
  has_many :students, through: :participations
  has_many :subject_item_notes
  belongs_to :teacher
  belongs_to :student


  validates :title, presence: true

  scope :not_assigned_or_assigned_to_teacher, -> (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,然后出现这个错误。

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

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

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

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

您需要第一个关系,以便 ActiveRecord 能够首先识别正确的关系以进行查询,然后再进行迁移。想一想如果您调用 @student.subject_items 将生成的查询。它会通过第一个关系还是第二个关系。

你的关系应该是:

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