我有这样的模型:
学生:
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 .
此外,您有两个关系,从 Student
到 SubjectItem
。
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/