在rake db:create上初始化rails应用程序的简单方法

时间:2012-06-07 10:05:03

标签: ruby-on-rails

我写了我的rails(3.2.3)应用程序......

配置/ application.rb中:

# ...

class MyWebApp
  class Application < Rails::Application

    # ...

    config.before_initialize do
      $my_config = MyConfig.new
    end
  end
end

配置/ database.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 raise ::

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 calls: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变量的简单方法

1 个答案:

答案 0 :(得分:0)

您可以向任务添加依赖项,尝试将此行放在Rakefile的末尾:

namespace :db do 
  task :create => [:environment, :load_config]
end