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
4

1 回答 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
于 2012-05-04T20:58:31.880 回答