【问题标题】:How can I use the methods in ActiveRecord::ConnectionAdapters::SchemaStatements in isolation?如何单独使用 ActiveRecord::ConnectionAdapters::SchemaStatements 中的方法?
【发布时间】:2016-03-23 02:57:13
【问题描述】:

我正在编写一个可以在 postgresql 中编写但想使用 ActiveRecord 编写的脚本。我想使用的大多数方法都位于ActiveRecord::ConnectionAdapters::SchemaStatements。因为这是一个模块,我如何在 ActiveRecord::Base.transaction 块中使用这些方法。我已经尝试过像这样直接调用方法:

ActiveRecord::ConnectionAdapters::SchemStatements.drop_table etc.

这似乎不起作用。甚至可以像这样使用 ActiveRecord 吗?

【问题讨论】:

  • 感谢您的回复,但它并不是我想要的。我熟悉连接到数据库,例如链接问题的引用方式,但我需要使用 ActiveRecord::Base 之外的方法来删除约束等。
  • 我明白了,我认为您仍然可以使用 ActiveRecord::Base 的方法,请参阅我的答案。

标签: ruby-on-rails activerecord


【解决方案1】:

需要active_recordestablish 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

【讨论】:

    【解决方案2】:

    我最近不得不做同样的事情,是的,这是可能的。我从一个常规的 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_manybelongs_to 等语句而不会出现任何问题。

    希望这足以让您入门。如果您需要更多详细信息,请告诉我。

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      相关资源
      最近更新 更多