postgresql - ActiveRecord - 无需 Rails 即可创建数据库

标签 postgresql activerecord

如果 ActiveRecord 不存在,我无法找到如何从中创建数据库。我看过这个:http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html#method-i-create_database ,但据我所知,它不想玩得很好......我不确定我在这里错过了什么。这可能吗?

谢谢!

最佳答案

我设法拼凑了这个既适用于 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

问题已解决。

关于postgresql - ActiveRecord - 无需 Rails 即可创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10476213/

相关文章:

ruby-on-rails - 如何递增属性,使其值(至少)比其他记录高 1 并且唯一

ruby-on-rails - 计算最近 7 天内创建的记录

postgresql - 如何在传递给应用程序的数据中包含 PostgreSQL 错误 where 子句?

c# - 如何使表/列名称的大写与 PetaPoco 和 PostgreSQL 无关?

java - ActiveJDBC 多个多对多关联

php - 无法加载请求的文件: home. php

ruby-on-rails - 如何在不实际执行的情况下获取由 ActiveRecord#find 创建的 SQL 语句?

sql - 没有结果的 Where 子句

sql - 具有跟踪考试类型能力的类(class)考试场景的数据库设计

postgresql - 如何将表示 postgresql 中的 HEX 八位字节的字符串转换为二进制?