Search code examples
ruby-on-railsrake

Rake db:migration against an existing DB


I have a new rails app that wil consume from an existing DB (created by another ruby application). To do so, I created a model for an already existing database table, but now rails gives me the error message that I have to run

rake db:migration

But if I try to do so, I get an error because the table already exists.

Is there any way to perform the migration and ignore existing tables? The table is correct, should be there and is filled with data coming for another application. I would like to have this application to consume the information.

Thanks

Edit: The DB settings are fine because I was able to perform db:migrations before. I created the model using

rails g model fundo

(fundo is the name of the model and fundoS is the name of the table) the model has no property yet, but the table has columns

Edit 2: These are the output if I run with --trace

$ rake db:schema:dump --trace

** Invoke db:schema:dump (first_time)

** Invoke environment (first_time)

** Execute environment

** Invoke db:load_config (first_time)

** Execute db:load_config ** Execute db:schema:dump

$ rake db:migrate --trace

** Invoke db:migrate (first_time)

** Invoke environment (first_time)

** Execute environment

** Invoke db:load_config (first_time)

** Execute db:load_config

** Execute db:migrate == CreateFundos: migrating ===================================================

-- create_table(:fundos) rake aborted! An error has occurred, this and all later migrations canceled: PG::DuplicateTable: ERROR: relation "fundos" already exists CREATE TABLE "fundos" ("id" serial primary key, "created_at" timestamp, "updated_at" timestamp)

It seems that rails is trying to recreate the tables. But I just want them to sync because the table is already there!


Solution

  • If you create models for already existing tables using rails g model, just delete the migration file that is created.

    The table schema will be dumped correctly in schema.rb, so can always be created from scratch on other machines with rake db:setup, even without the migration file.

    You can use rake db:schema:dump to update schema.rb manually.