Rails db:migrate relation does not exist

£可爱£侵袭症+ 提交于 2019-12-31 02:49:31

问题


I have such models:

student:

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

and 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

And migration:

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

But when I do rake db:migrate

I get error:

== 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"

In panic I was rebuilding the db many times and probobly made some mess in the schema .... :(

As for now I try to make:

rake db:drop then rake db:create and rake db:migrate, and then this error ocurs.


回答1:


First, check your sequence of migrations. It seems that you are trying to create a reference before creating the table subject_items itself.

You should first create students table then your subject_items table then add the reference. Or alternatively add the reference columns yourself when creating the tables which is all what add_reference does.

Also, You have two relations from Student to SubjectItem.

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

You need to your first relation in order for ActiveRecord to be able to identify the correct one first for querying then for your migration. Think of the query that will be generated if you called @student.subject_items for example. Will it go through the first relation or the second one.

Your relations should be ex:

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


来源:https://stackoverflow.com/questions/34117031/rails-dbmigrate-relation-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!