ruby-on-rails - rails 数据库 :migrate relation does not exist

标签 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"

在 panic 中,我多次重建数据库,可能在模式中造成了一些困惑...... :(

至于现在我试着做:

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

最佳答案

首先,检查您的迁移顺序。看来您正在尝试在创建表 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 将生成的查询。它会通过第一个关系还是第二个关系。

你的关系应该是:

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

关于ruby-on-rails - rails 数据库 :migrate relation does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117031/

相关文章:

javascript - 如何使用每个 ajax 请求更新实例变量?

Android Phonegap 数据库

c - c99 的 ansi c 结构初始化

mysql - rails应用中不同电脑访问数据库

ruby-on-rails - Nokogiri 无法安装 native 扩展问题

c# - 如何将 Oracle 数据库 NUMBER 映射到 .NET Core 中的 c# bool 类型?

django - 如何按计算属性的总和对 Django 模型进行排序?

javascript - 文件选择器.io : merging accounts or cloning files and urls from one to another

ruby-on-rails - 创建迁移文件时分配默认值

ruby-on-rails - 将 OAuth 与 ActiveResource 一起使用的最简单方法是什么?