zyriuse
zyriuse

Reputation: 73

how i can i check the existence of the table

hy

A lot of time when i run rake db:migrate i get an error because the table user or foor or bar exist. I try to check the existence of table, but that didn't work and i dont know why . I use rails 3.2.2

class AddDeviseToUsers < ActiveRecord::Migration

    #def self.table_exists?(users)
    #  ActiveRecord::Base.connection.tables.include?(users)
    #end

     if !table_exists?("users")
        def change
          create_table(:users) do |t|
             ## Database authenticatable
           t.string :email, :null => false, :default => ""
           t.string :encrypted_password, :null => false, :default => ""
    end
  end
end

Upvotes: 0

Views: 6102

Answers (3)

Catfish
Catfish

Reputation: 19294

You should never have multiple migrations that both try to create the same table. You also should not experience errors like this if you're working with rails migrations correctly.

The way rails migrations work is that every time you run rake db:migrate, for every migration file that runs successfully, it stores the number part of the migration file 123456789_create_users_table.rb (123456789 in this case) in a table in your db called schema_migrations. This way if a migration has already been run, it will never get run again.

It doesn't sound like you're working with rails migrations correctly. I suggest reading this thoroughly: http://guides.rubyonrails.org/migrations.html

Upvotes: 0

gcoderre
gcoderre

Reputation: 91

You can check the existence of a table with the following command. This question has already been posted and answered here.

ActiveRecord::Base.connection.table_exists? 'users'

However, your code contains errors. You cannot define a method inside an if block with the syntax you're using. Put the block inside your method, instead.

def change
  if !table_exists?("users")
    # ...
  end
end

Also, you should not be getting this kind of errors often, as you state. Migrations are applied sequentially. Creating your users table in a separate migration before adding Devise to it would take care of that problem. If you run into this problem while migrating an existing project from scratch, consider using rake db:schema:load instead.

Upvotes: 9

sabrams
sabrams

Reputation: 1128

In your command terminal type in sqlite3 db/development.sqlite3 then you can search through your database by SQL command. Use .tables to list all tables in the database and you can see if yours is missing or not.

You can also just look at your schema file to see if the migration worked. The table along with all of it's attributes will be listed there.

Upvotes: 0

Related Questions