ActiveRecord without Rails

Say you want ORM with a console script.

Here’s how you could do it using ActiveRecord without Rails.

1. create a database YAML file (a la Rails) 

2. Use the ActiveRecord::Base.establish_connection

Super simple. E.g. 

require ‘rubygems’

require ‘active_record’

require ‘yaml’

require ‘mysql2’

require ‘logger’

dbconfig = YAML::load(File.open(‘database.yml’))

ActiveRecord::Base.establish_connection(dbconfig)

class People < ActiveRecord::Base

end

puts People.count

(assuming you had a MySQL database table called ‘people’) with a database.yml like this:

adapter:  mysql2

database: your_database

username: user

password: your_pass

host:     localhost

and you could log it using:

ActiveRecord::Base.logger = Logger.new(STDERR)

See also:

http://blog.aizatto.com/2007/05/21/activerecord-without-rails/

https://adaptivekanban.com/blog/2012/05/dead-simple-activerecord-migrations-without-rails/

Leave a Reply

Your email address will not be published. Required fields are marked *