首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查mysql表是否已存在

问检查mysql表是否已存在
EN

Stack Overflow用户
提问于 2012-05-05 04:22:56
回答 1查看 915关注 0票数 3

我使用activerecord连接到mysql数据库,并在连接后创建表。到目前为止,它工作得很好,问题是我不知道如何检查表是否已经存在。我以为它能和table.exist一起工作呢?但不知何故我没有......So这是我到目前为止得到的:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-05 04:58:32

您需要在数据库连接上使用#tables方法。

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10455645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档