ajk4550
ajk4550

Reputation: 741

Rails migration schema issue

In my rails App I have three models/tables in the database (users, registrants, events). I was setting up some Capybara/RSpec tests when I ran into an issue saying it could not find the events table.

Now the events model has been working fine, I've been able to create events, go into the rails console and query things such as Events.all or Events.find(1). What is confusing me is my schema. My schema has

create_table "registrations", force: true do |t|
    t.string   "first_name"
    ...
end

create_table "users", force: true do |t|
    t.string   "email",                  default: "",    null: false
    ...
end

But there is no reference to the events table. It's been some time since I generated the model for Events but here is the migration:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table(:events) do |t|
      t.string :name
      t.string :location

      t.timestamps
    end
  end
end

I have ran commands such as rake db:reset and rake db:migrate to make sure all my migrations are current. Any ideas why the events table is not in the schema?

UPDATE: So I've deleted the DB and Schema and began migrating each migration one at a time. The events table is there when I run the migration to create it, but after I run the following command the table disappears from the schema:

class AddingAssociationsToEventsUserModels < ActiveRecord::Migration
  def change
    add_column :events, :belongs_to, :user, index: true
  end
end

Here is the migration being run:

rake db:migrate:redo VERSION=20150518132834
== 20150518132834 AddingAssociationsToEventsUserModels: migrating =============
-- add_column(:events, :belongs_to, :user, {:index=>true})
   -> 0.0006s
== 20150518132834 AddingAssociationsToEventsUserModels: migrated (0.0006s) ====

Upvotes: 0

Views: 634

Answers (2)

ajk4550
ajk4550

Reputation: 741

Ok so the issue was a mistake in my migration file. Here is what I changed my migration to:

class AddingAssociationsToEventsUserModels < ActiveRecord::Migration
  def change
    add_reference :events, :user, index: true
  end
end

Now the events table is in my Schema and the test can find the table and is passing!

Upvotes: 1

Jorge de los Santos
Jorge de los Santos

Reputation: 4633

That's because test database and development database are not matched.

Run:

RAILS_ENV=test rake db:drop && rake db:create && rake db:migrate

or

RAILS_ENV=test rake db:test:prepare

or

RAILS_ENV=test rake db:reset

Any of the above should work.

Upvotes: 3

Related Questions