[英]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.我正在构建一个使用 ActiveRecord 的非 Rails 纯 ruby 应用程序。我想编写一个 rake 文件来为其创建数据库和表。 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.
好吧,这很明显,因为我没有将 ActiveRecord 连接到任何数据库。
What should I do?我应该怎么办?
EDIT: I want to create a MySQL database.编辑:我想创建一个 MySQL 数据库。
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. 对于sqlite,如果数据库(文件)不存在,则会创建它。 Then perform a migration to create the tables.
然后执行迁移以创建表。
Based on a previous question Can ActiveRecord create tables outside of a migration? 基于上一个问题, ActiveRecord可以在迁移之外创建表吗?
Thanks for answers but as I've edited in my question, I forgot to mention that I want to create a MySQL DB. 感谢您的回答,但正如我在我的问题中编辑的那样,我忘了提到我想创建一个MySQL数据库。 I've failed to create a MySQL db via ActiveRecord.
我无法通过ActiveRecord创建MySQL数据库。 Then I've solved the problem with the help of mysql2 gem.
然后我在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. 这里'USE company_db'查询很重要,因为它告诉gem我们要在这个数据库上运行查询。
You can use the create_database
method off of the connection like so: 您可以使用连接的
create_database
方法,如下所示:
ActiveRecord::Base.establish_connection(connetion_params)
ActiveRecord::Base.connection.create_database('database_name')
You need to connect without the database, then create it, then connect with the database:您需要在没有数据库的情况下连接,然后创建它,然后连接数据库:
connection_options = { adapter: "mysql2", host: "127.0.0.1", username: "root" }
database = 'foo'
ActiveRecord::Base.establish_connection(connection_options)
begin
ActiveRecord::Base.connection.create_database(database)
rescue ActiveRecord::StatementInvalid
# already exists ...
end
ActiveRecord::Base.establish_connection(connection_options.merge(database: database))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.