2

Is there a way within Rails/AR to create a new mysql database at runtime?

2
  • 1
    Do 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? Commented 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. Commented Nov 4, 2010 at 13:09

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

The quick and dirty answer is:

  1. Make sure the MySQL user your app is connecting as is allowed to create databases.

  2. 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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.