2012-05-07 9 views
0

ActiveRecordからデータベースを作成する方法が見つからない場合は、まだ存在しません。私はこれを見てきました:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html#method-i-create_databaseしかし、それは私が言うことができる限り、素晴らしい再生したくない...私はここで何が欠けているか分からない。これも可能ですか?ActiveRecord - Railsなしでデータベースを作成する

ありがとうございます!

+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 

問題を解決しました。

関連する問題