13

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?

Kamil Lelonek
  • 14,592
  • 14
  • 66
  • 90
  • 1
    Possible duplicate of [How to use ActiveRecord in a ruby script outside Rails?](http://stackoverflow.com/questions/1643875/how-to-use-activerecord-in-a-ruby-script-outside-rails) – Mogsdad Mar 08 '16 at 21:04
  • If you want something that works. Here is an example. Run bundle install & migrate your DB. Your done. README for more info. https://github.com/slindsey3000/ContactManager – slindsey3000 Mar 22 '16 at 19:12
  • Related: [*Generate migrations outside Rails*](https://stackoverflow.com/questions/11882345/generate-migrations-outside-rails) – Franklin Yu Dec 09 '18 at 03:57

2 Answers2

18

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

Austio
  • 5,939
  • 20
  • 34
2

An updated solution is the standalone_migrations. Basically after doing the configuration for the gem and creating the configuration, you have access to all the ActiveRecord niceties. Rake tasks included!

Also, I made a small generator for scaffolding simple scripts that have access to ActiveRecord out of the box: nrb - Ninja Ruby.

stfcodes
  • 1,380
  • 1
  • 9
  • 18