How to use ActiveRecord outside Rails?

Kamil Lelonek picture Kamil Lelonek · Dec 21, 2014 · Viewed 7.5k times · Source

I'm building a Rails application based on hexagonal architecture.

One of my adapters is storage adapter (maintained as a gem) that manages access to database and provides simple interface for rails application to store and query data in database.

I'd like to use ActiveRecord in this gem with all rake tasks (create, migrate, drop, rollback) for managing database.

How can I use AR outside rails, but with all rake tasks?

Answer

Austio picture Austio · Dec 21, 2014

Install it like any other gem

gem install activerecord

Then you configure it somewhere like this

ActiveRecord::Base.establish_connection(
  :adapter  => 'mysql',
  :database => 'database',
  :username => 'user',
  :password => 'password',
  :host     => 'localhost')

Models can then inherit as normal from ActiveRecord::Base

You get all of the rake tasks but you do have to do some extra configuration since you will not have the Rails. Here is the link inside of activerecord for how to configure that stuff.

Database tasks