【问题标题】:Add records from external ruby script从外部 ruby​​ 脚本添加记录
【发布时间】:2008-12-17 02:52:14
【问题描述】:

从外部脚本向数据库添加记录的最佳方式是什么。我想使用 activerecord,但我不确定如何在 rails 目录结构之外使用。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以在 ruby​​ 中使用 activerecord。假设您已经安装了所需的数据库驱动程序。你可以做类似的事情

    require 'activerecord'
    
    ActiveRecord::Base.establish_connection(
      :adapter => 'your_database_adapter',
      :host => 'your_host',
      :username => 'username'
      :password => 'password',
      :port => 'port_number'
    )
    

    建立数据库连接。由于您想将记录添加到数据库,我假设架构已经存在。然后你只需做

    class ModelName < ActiveRecord::Base
      has_many :modelz
    end
    
    class Modelz < ActiveRecord::Base
      belongs_to :model_name
    end
    

    你已经准备好了。 (没错,一旦建立数据库连接,您就可以使用活动记录在 Rails 中做任何事情,甚至在模型之间建立关系)您可以对刚刚创建的模型类的对象做任何您想做的事情。喜欢,

    ModelName.find(:all)
    
    @model = ModelName.new
    @model.user_id = rand(10)
    @model.save
    

    等等等等

    如果您没有适当的架构,请不要惊慌。建立数据库连接后,您可以通过嵌入代码来创建它。

    ActiveRecord::Schema.define do
      create_table :sometable do |table|
        table.integer :int1, :int2
        table.string :str1, :str2
      end
    
      create_table :yetanothertable do |table|
        table.integer :anotherint
        table.text :sometext
      end
    end
    

    这应该可以正常工作。这里给出的代码是一个示例,在语法上可能并不完美。 This should also help. 但是,模式定义是用旧的 rails 方式完成的。

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 2014-09-15
      • 2022-06-11
      • 2014-07-26
      • 2022-12-21
      • 2014-02-21
      • 1970-01-01
      • 2012-05-02
      • 2021-12-26
      相关资源
      最近更新 更多