我写了我的rails(3.2.3)应用程序......
配置/应用程序.rb:
# ...
class MyWebApp
class Application < Rails::Application
# ...
config.before_initialize do
$my_config = MyConfig.new
end
end
end
配置/数据库.yml:
development:
adapter: mysql2
encoding: utf8
reconnect: true
database: <%=$my_config.config['db']['basename']%>_development
pool: 5
username: <%=$my_config.config['db']['username']%>
password:
socket: /var/run/mysqld/mysqld.sock
然后, rake db:create 引发:
rake aborted!
undefined method `config' for nil:NilClass
(erb):15:in `<main>'
/home/sn/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/erb.rb:838:in `eval'
/home/sn/.rbenv/versions/1.9.3-p194/lib/ruby/1.9.1/erb.rb:838:in `result'
/home/sn/dev/mywebapp/vendor/bundle/ruby/1.9.1/gems/railties-3.2.3/lib/rails/application/configuration.rb:115:in `database_configuration'
...
在我手动创建数据库后, rake db:migrate 成功。所以我阅读了 databases.rake 并发现 db:migrate 调用 :environment task 但 db:create 没有。
activerecord-3.2.3/lib/active_record/railties/databases.rake:
task :create => :load_config do
configs_for_environment.each { |config| create_database(config) }
ActiveRecord::Base.establish_connection(configs_for_environment.first)
end
task :migrate => [:environment, :load_config] do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, ENV["VERSION"] ? ENV["VERSION"].to_i : nil) do |migration|
ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope)
end
end
您知道在 rake db:create 上正确初始化 $my_config 变量的任何简单方法吗?