Rails db:migrate关系不存在

时间:2015-12-06 11:42:16

标签: ruby-on-rails database migration

我有这样的模特:

学生:

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,然后出现此错误。

1 个答案:

答案 0 :(得分:1)

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

首先应创建学生表,然后创建subject_items表,然后添加参考。或者在创建表格时自己添加引用列,这些都是add_reference does

此外,您有两个从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