简体   繁体   中英

How to create a new MySQL database with ActiveRecord in a non-rails app?

I'm building a non-rails pure ruby app that uses ActiveRecord. I want to write a rake file that creates a database and tables for it. I try the following code

namespace :db do
  task :create do
    conn = ActiveRecord::Base.connection
    create_db = "CREATE DATABASE foo_dev"
    conn.execute(create_db)
  end
end

But this gives me

ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished

error. Well, this is obvious because I didn't connect ActiveRecord to any database.

What should I do?


EDIT: I want to create a MySQL database.

Establish a Connection, some thing like:

ActiveRecord::Base.establish_connection(
   :adapter   => 'sqlite3',
   :database  => './your_db.db'
)

For sqlite the database (file) gets created if it does not exist. Then perform a migration to create the tables.

Based on a previous question Can ActiveRecord create tables outside of a migration?

Thanks for answers but as I've edited in my question, I forgot to mention that I want to create a MySQL DB. I've failed to create a MySQL db via ActiveRecord. Then I've solved the problem with the help of mysql2 gem. Here's my solution:

client = Mysql2::Client.new(:host => 'localhost', :username=>"#{YOUR_MYSQL_USERNAME}", :password=> "#{YOUR_MYSQL_PASSWORD}")
client.query("CREATE DATABASE company_db")
client.query('USE company_db')
client.query('CREATE TABLE employees ...')
...

Here 'USE company_db' query is important because, it tells to the gem that we want to run queries on this database.

You can use the create_database method off of the connection like so:

ActiveRecord::Base.establish_connection(connetion_params)
ActiveRecord::Base.connection.create_database('database_name')

You need to connect without the database, then create it, then connect with the database:

connection_options = { adapter: "mysql2", host: "127.0.0.1", username: "root" }
database = 'foo'
ActiveRecord::Base.establish_connection(connection_options)
begin
  ActiveRecord::Base.connection.create_database(database)
rescue ActiveRecord::StatementInvalid
  # already exists ...
end
ActiveRecord::Base.establish_connection(connection_options.merge(database: database))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM