0

hy

很多时候,当我运行 rake db:migrate 时,我收到一个错误,因为 table user 或 foor 或 bar 存在。我尝试检查表的存在,但这不起作用,我不知道为什么。我使用导轨 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
4

3 回答 3

8

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.

于 2013-11-14T00:16:23.467 回答
0

您永远不应该有多个迁移都尝试创建同一个表。如果您正确使用 rails 迁移,您也不应该遇到这样的错误。

rails 迁移的工作方式是每次运行时rake db:migrate,对于每个成功运行的迁移文件,它都会将迁移文件的数字部分123456789_create_users_table.rb(在本例中为 123456789)存储在名为schema_migrations. 这样,如果迁移已经运行,它将永远不会再次运行。

听起来您没有正确使用 rails 迁移。我建议彻底阅读:http: //guides.rubyonrails.org/migrations.html

于 2013-11-14T15:39:36.543 回答
0

在您的命令终端中输入, sqlite3 db/development.sqlite3 然后您可以通过 SQL 命令搜索您的数据库。用于.tables列出数据库中的所有表,您可以查看您的表是否丢失。

您也可以只查看您的架构文件以查看迁移是否有效。该表及其所有属性将在此处列出。

于 2013-11-13T23:56:39.097 回答