Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查mysql表是否已经存在_Mysql_Ruby_Activerecord - Fatal编程技术网

检查mysql表是否已经存在

检查mysql表是否已经存在,mysql,ruby,activerecord,Mysql,Ruby,Activerecord,我使用activerecord连接到mysql数据库,并在连接后创建一个表。 到目前为止,它工作得很好,问题是我不知道如何检查表是否已经存在。我以为它会和桌子一起工作。存在吗?但不知为什么我没有。。。 …到目前为止,我得到的是: ActiveRecord::Base.establish_connection( :adapter => "mysql", :host => "localhost", :username => "my-u

我使用activerecord连接到mysql数据库,并在连接后创建一个表。 到目前为止,它工作得很好,问题是我不知道如何检查表是否已经存在。我以为它会和桌子一起工作。存在吗?但不知为什么我没有。。。 …到目前为止,我得到的是:

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
ActiveRecord::Base.build\u连接(
:adapter=>“mysql”,
:host=>“localhost”,
:username=>“我的用户名”,
:password=>“我的密码”,
:database=>“我的数据库”,
:encoding=>“UTF8”
)
#如何检查它是否已经存在?表_name.table.exist?真的不管用。。。
name=“我的表格”
如果你的名字。!表1.存在吗?
ActiveRecord::Schema.define do
创建_表:“#{name}”do|表|
table.column:foo,:string
table.column:bar,:string
结束
结束
其他的
放置“表已存在…”
结束
#为mysql表创建ActiveRecord对象
类表
您需要在数据库连接上使用#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