【问题标题】:Seed Data onto Database in an ruby program using activerecord使用 activerecord 在 ruby​​ 程序中将数据播种到数据库中
【发布时间】:2026-02-24 10:30:02
【问题描述】:

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

到目前为止,我的代码是:

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

【问题讨论】:

  • 我的现有代码列在给定的链接中:pastebin.com/f25KQfum
  • 分享有问题的代码,而不是链接到其他馅饼或要点。
  • @Wand Maker 我很想发帖,但由于我是初学者并且不需要声誉点来发布代码,所以我不允许这样做

标签: ruby activerecord seeding


【解决方案1】:
  1. 确保仅在表不存在时才创建表:

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

    结束

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

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

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

【讨论】:

    最近更新 更多