[英]Active Record error to create database
In my spec/rails_helper.rb , i have the code bellow to create the test database if it doesn`t exits. 在我的spec / rails_helper.rb中 ,如果没有退出,我有下面的代码可以创建测试数据库。
def database_exists?
ActiveRecord::Base.connection rescue ActiveRecord::NoDatabaseError ? false : true
end
unless database_exists?
ActiveRecord::Base.establish_connection(:"#{ENV['RAILS_ENV']}")
db_config = ActiveRecord::Base.configurations[ENV['RAILS_ENV']]
ActiveRecord::Base.connection.create_database db_config
end
but i got this error when rspec is called: 但是当调用rspec时出现此错误:
.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/mysql2_adapter.rb:23:in `rescue in mysql2_connection': Unknown database 'my-db-test' (ActiveRecord::NoDatabaseError)
.rbenv / versions / 2.2.1 / lib / ruby / gems / 2.2.0 / gems / activerecord-4.2.1 / lib / active_record / connection_adapters / mysql2_adapter.rb:23:在mysql2_connection中的救援中:未知数据库my -db-test'(ActiveRecord :: NoDatabaseError)
Where is the problem? 问题出在哪儿?
If i use system('rake db:create') , it works, but is a good pratice? 如果我使用system('rake db:create') ,它可以工作,但是是一个很好的实践吗?
The database doesn't exist so to avoid the error you can run: 该数据库不存在,因此为了避免错误可以运行:
rake db:create
or you can run: 或者您可以运行:
rake db:setup
This will create the database AND run the migration files. 这将创建数据库并运行迁移文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.