检查mysql表是否已经存在。

3

我使用activerecord连接到mysql数据库,并在连接后创建了一张表。 目前它运行得很好,问题是我不知道如何检查表是否已经存在。我认为可以用table.exist?来解决,但是不知道为什么没有成功... ... 这是我到目前为止的代码:

ActiveRecord::Base.establish_connection(
        :adapter => "mysql",
        :host => "localhost",
        :username => "my-username",
        :password => "my-password",
        :database => "my-db",
        :encoding => "UTF8"
    )

    # How to check if it exists already? table_name.table.exist? doesnt really work...
    name = "my_table"
if name.!table.exist?
    ActiveRecord::Schema.define do
        create_table :"#{name}" do |table|
            table.column :foo, :string
            table.column :bar, :string
        end
    end
else
puts "Table exist already..."
end
    # Create ActiveRecord object for the mysql table
    class Table < ActiveRecord::Base
        set_table_name "#{name}"
    end
1个回答

1
您需要在数据库连接上使用 #tables 方法。
unless ActiveRecord::Base.connection.tables.include? name
  ActiveRecord::Schema.define do
    create_table :"#{name}" do |table|
      table.column :foo, :string
      table.column :bar, :string
    end
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接