2012-05-07 29 views
0

我無法找到如何從ActiveRecord創建數據庫(如果尚不存在的話)。我已經看過這個:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html#method-i-create_database,但它不想打得很好,據我所知...我不知道我在這裏錯過了什麼。這甚至有可能嗎?ActiveRecord - 創建一個沒有導軌的數據庫

謝謝!

+0

問題說沒有Rails,但你引用了一個Rails頁面。你不能解釋你已經嘗試了什麼,或者你的意思是「它不想玩得好」。 – kgrittn

+0

我正在使用[Goliath](https://github.com/postrank-labs/goliath/)和ActiveRecord。當時我不能更具體,因爲我真的不知道發生了什麼。我很抱歉過於簡單。 – wulftone

回答

4

我設法將這個與heroku和我的本地機器一起工作的東西拼湊在一起,並創建一個數據庫(如果不存在的話)。

# ./lib/db_connect.rb 

require 'erb' 
require 'uri' 
require 'em-synchrony/activerecord' 

class DbConnect 
    attr_accessor :config 
    def initialize 
    @db = URI.parse(ENV['DATABASE_URL'] || 'http://localhost') 
    if @db.scheme == 'postgres' # This section makes Heroku work 
     ActiveRecord::Base.establish_connection(
     :adapter => @db.scheme == 'postgres' ? 'postgresql' : @db.scheme, 
     :host  => @db.host, 
     :username => @db.user, 
     :password => @db.password, 
     :database => @db.path[1..-1], 
     :encoding => 'utf8' 
    ) 
    else # And this is for my local environment 
     environment = ENV['DATABASE_URL'] ? 'production' : 'development' 
     @db = YAML.load(ERB.new(File.read('config/database.yml')).result)[environment] 
     ActiveRecord::Base.establish_connection(@db) 
     @config = ActiveRecord::Base.connection.pool.spec.config 
    end 
    end 
end 

# connect to the database 
DbConnect.new 

這裏有一個使用它的Rakefile。

# ./Rakefile 

$: << './lib' 
require 'db_connect' 

db = DbConnect.new 
config = db.config 

desc 'create the database' 
task :create_db do 
    unless ENV['DATABASE_URL'].present? 
    ActiveRecord::Base.establish_connection adapter:'postgresql',username:config[:username],password:config[:password], database: 'postgres' 
    ActiveRecord::Base.connection.create_database config[:database] 
    else 
    raise StandardError, "You cannot do this on Heroku!" 
    end 
end 

desc 'create the users table' 
task :create_users_table do 
    ActiveRecord::Schema.define(:version => 0) do 
    create_table "users", :force => true do |t| 
     t.string "first_name" 
     t.string "last_name" 
     t.datetime "created_at", :null => false 
     t.datetime "updated_at", :null => false 
    end 
    end 
end 

問題解決了。