Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails db:migrate relation does not exist

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.

like image 758
Kazik Avatar asked Sep 14 '25 13:09

Kazik


1 Answers

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
like image 121
Oss Avatar answered Sep 16 '25 08:09

Oss