Creating databases on the fly

Hi,

Is there a recommended way of creating a new database from within
rails? (or is the recommended way not to do it?)

In my application I wish to be able to create a new database structure
for each user who signs up, but there doesn’t seem to be a way of doing
this using ActiveRecord.

At present I can create it by establishing a new connection to the
database
dbh = Mysql.real_connect(…)
then doing something like this
dbh.query("create database " + database_name)
which works fine with my windows machine (with mysql-win gem installed)
but not my linux server.

Any advice is greatly appreciated.
Many thanks
Tim

Migrations, maybe? Search for that on the rails wiki.

Tim,

You can use the ActiveRecord connection adapters, something like:

ActiveRecord::Base.connection.execute(“CREATE DATABASE #{db_name}”)

However you better be very sure to sanitize that incoming data. The
statement above on its own is ripe for SQL injection.

V/r
Anthony E.

On 12/1/06, Tim L. [email protected] wrote:

At present I can create it by establishing a new connection to the


Cell: 808 782-5046
Current Location: Melbourne, FL

In my application I wish to be able to create a new database structure
for each user who signs up, but there doesn’t seem to be a way of doing
this using ActiveRecord.

Are you absolutely sure that’s what you want? Usually this leads to all
kinds of horrible problems. If you just want to support multiple,
separate accounts in your application, you do not want to use separate
databases. Instead, just have your content tables reference an account
table and use the object hierarchy to protect against data bleeding.

class Account < ActiveRecord::Base
has_many :people
end

class Person < ActiveRecord::Base
belongs_to :account
end

Then you find some way of identifying which account someone is using
(like a subdomain in the URL is common) and load that into @account.
Now you can do @account.people.find(params[:id]) and rest assured that
nobody will be able to access people from outside of their own account.