如何在外面的Rails的Ruby脚本使用ActiveRecord? [英] How to use ActiveRecord in a ruby script outside Rails?

查看:118
本文介绍了如何在外面的Rails的Ruby脚本使用ActiveRecord?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的Ruby脚本中,我想使用ActiveRecord轻松地访问一个数据库模型。什么是做到这一点的最好方法是什么?

解决方案

 要求'active_record
要求'mysql2'#或PG'或'sqlite3的'

#更改以下,以反映您的数据库设置
的ActiveRecord :: Base.establish_connection(
  适配器:mysql2,#或PostgreSQL的'或'sqlite3的
  主持人:'localhost'的,
  数据库:'your_database,
  用户名:your_username,
  密码:your_password
)

#定义你的类基于数据库的,一如既往
类SomeClass的<的ActiveRecord :: Base的
  #等等等等等等
结束

#现在做的东西与它
把SomeClass.find:所有
some_class = SomeClass.new
 

I have a small ruby script in which I'd like to use ActiveRecord to easily access a database model. What is the best way to do it?

解决方案

require 'active_record'
require 'mysql2' # or 'pg' or 'sqlite3'

# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
  adapter:  'mysql2', # or 'postgresql' or 'sqlite3'
  host:     'localhost',
  database: 'your_database',
  username: 'your_username',
  password: 'your_password'
)

# Define your classes based on the database, as always
class SomeClass < ActiveRecord::Base
  #blah, blah, blah
end

# Now do stuff with it
puts SomeClass.find :all
some_class = SomeClass.new

这篇关于如何在外面的Rails的Ruby脚本使用ActiveRecord?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆