How to create a new MySQL database with ActiveRecord in a non-rails app?

眉间皱痕 提交于 2019-12-10 21:25:19

问题


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"
    conn.execute(create_db)
  end
end

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.


回答1:


Establish a Connection, some thing like:

ActiveRecord::Base.establish_connection(
   :adapter   => 'sqlite3',
   :database  => './your_db.db'
)

For sqlite the database (file) gets created if it does not exist. Then perform a migration to create the tables.

Based on a previous question Can ActiveRecord create tables outside of a migration?




回答2:


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 = Mysql2::Client.new(:host => '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.




回答3:


You can use the create_database method off of the connection like so:

ActiveRecord::Base.establish_connection(connetion_params)
ActiveRecord::Base.connection.create_database('database_name')


来源:https://stackoverflow.com/questions/14161229/how-to-create-a-new-mysql-database-with-activerecord-in-a-non-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!