我有一个小的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