Is there a way within Rails/AR to create a new mysql开发者_运维问答 database at runtime?
What i recommend is to prepare standalone script readable only by specified user and execute it from rails with system
command with db name as parammeter
The quick and dirty answer is:
Make sure the MySQL user your app is connecting as is allowed to create databases.
Create the database using a SQL statement:
ActiveRecord::Base.connection.execute('CREATE DATABASE IF NOT EXISTS new_database');
For simplicity's sake I'd suggest not even using ActiveRecord for this. AR is really designed to work with preconfigured databases, and even though you can create databases where you'll really run into problems is in trying to connect to and use those DBs on the fly.
You might be better off using Brian Lopez's mysql2 gem (in addition to AR for your app's main DB):
https://github.com/brianmario/mysql2
In addition to being pretty fast and modern, its API is a lot easier to work with than the raw mysql library (which is what AR uses under the hood, including connection.execute).
精彩评论