使用 activerecord 在 ruby 程序中将数据播种到数据库中

Seed Data onto Database in an ruby program using activerecord

如何在独立 ruby 程序中使用活动记录将一些数据播种到 table?

到目前为止我的代码是:

require 'prawn'
require 'active_record'
require 'pg'

ActiveRecord::Base.establish_connection(
  adapter:  'postgresql',
  host:     'localhost',
  database: 'sample',
  username: 'postgres',
  password: '...'
)

ActiveRecord::Schema.define do
  create_table :xmldata, force: true do |t|
    t.text :xmlstr
  end
end
  1. 确保仅在 table 不存在时才创建它:

    ActiveRecord::Schema.define do
      if not connection.table_exists? :xmldata
        create_table :xmldata, force: true do |t|
          t.text :xmlstr
        end
      end
    end
    

    结束

  2. 为 table 创建一个 ActiveRecord 模型。

    class Xmldata < ActiveRecord::Base
    end
    
  3. 创建对象并保存它们

    Xmldata.create({xmlstr: "<person><name>SOuser</name></person>"})