İlker İnanç İlker İnanç - 1 year ago 81
Ruby Question

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"

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.

Answer Source

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 = => '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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download