Is there a way within Rails/AR to create a new mysql database at runtime?
-
1Do you mean to create the database, or to create a database, as in, to make additional databases that are used by the application in conjunction with the main one?tadman– tadman2010-11-04 04:01:43 +00:00Commented Nov 4, 2010 at 4:01
-
I'm looking to be able to create multiple databases, one per customer the app will be smart enough to connect to the correct db based upon who the user is authenticated as.Chris Dellinger– Chris Dellinger2010-11-04 13:09:58 +00:00Commented Nov 4, 2010 at 13:09
2 Answers
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).