I use activerecord to connect to mysql database and to create a table after connection. While it works fine, the problem is that I don't know how to check if the table exists. I thought this would work with table.exist? but somehow I don’t ... ... So this is what I got so far:
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "my-username",
:password => "my-password",
:database => "my-db",
:encoding => "UTF8"
)
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
class Table < ActiveRecord::Base
set_table_name "#{name}"
end
source
share