我正在编写一个脚本,我可以在postgresql中编写,但想使用ActiveRecord编写。我想使用的大部分方法都位于ActiveRecord::ConnectionAdapters::SchemaStatements。因为这是一个模块,我如何在ActiveRecord::Base.transaction
块中使用这些方法。我已经尝试过直接调用这些方法:
ActiveRecord::ConnectionAdapters::SchemStatements.drop_table etc.
这似乎不起作用。甚至可以像这样使用ActiveRecord吗?
答案 0 :(得分:0)
您需要active_record
,establish a connection to the database,然后您可以通过connection
方法使用所有方法:
# test.rb
require 'active_record'
require 'pg'
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'postgresql',
host: 'localhost',
database: 'database',
username: 'username',
password: 'passwd'
)
puts ActiveRecord::Base.connection.table_exists?('users')
测试运行(当我的数据库中确实存在users
表时):
$ ruby test.rb
true
答案 1 :(得分:0)
我最近不得不做同样的事情,是的,这是可能的。我开始使用常规的Rails项目(rails new app
)并将其剥离以满足我的需求。
我的最终项目结构只有以下文件夹和文件(其他所有内容都已删除):
/app/models/*
/bin/bundle
/bin/rake
/bin/spring
/config/application.rb
/config/boot.rb
/config/database.yml
/config/environment.rb
/config/environments/*
/db/schema.rb
/config.ru
/Gemfile
/Gemfile.lock
/Rakefile
我的Gemfile
包含:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '< 5.0.0'
# Use mysql as the database for Active Record
gem 'mysql2' # <-- change this to PostgreSQL
我还有一个脚本app.rb
,我把它放在项目的根目录中:
# ensure that all dependent gems are installed before running
require_relative 'config/boot'
# include dependent libraries
require 'active_record'
require 'active_model'
require 'mysql2' # <-- change this to PostgreSQL
require 'yaml'
# set up environment and connect to the database
environment = ENV['RAILS_ENV'] || 'development'
database = YAML.load_file('config/database.yml')
ActiveRecord::Base.establish_connection database[environment]
# set up logging so you can use $logger.debug or $logger.info anywhere in your code
$logger = Logger.new(File.new("log/#{environment}.log", 'w'))
$logger.level = environment == 'development' ? Logger::DEBUG : Logger::INFO
# include dependent classes in same directory
# this step is optional as the required files can be included as needed
Dir['app/models/*.rb'].each { |file| require_relative file }
现在,假设您在User
中定义了一个名为/app/models/user.rb
的模型
class User < ActiveRecord::Base
end
然后,您可以在app.rb
:
#execute code as a single transaction
ActiveRecord::Base.transaction do
user1 = User.create!(first_name: 'Richard', last_name: 'Rahl')
user2 = User.create!(first_name: 'Kahlan', last_name: 'Amnell')
end
您甚至可以在模型中使用has_many
,belongs_to
等语句,而不会出现任何问题。
希望这足以让你入门。如果您需要更多详细信息,请与我们联系。