从外部脚本向数据库添加记录的最佳方法是什么。我想使用 activerecord,但我不确定如何在 rails 目录结构之外使用它。
最佳答案
您可以在 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
等等等等
如果您没有合适的架构,请不要 panic 。您可以在建立数据库连接后通过嵌入类似于以下的代码来创建它。
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 方式完成的。
关于ruby-on-rails - 从外部 ruby 脚本添加记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/373524/