How to use ActiveRecord in a ruby script outside Rails?

Ruby on-RailsRubyActiverecordScripting

Ruby on-Rails Problem Overview

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?

Ruby on-Rails Solutions

Solution 1 - Ruby on-Rails

require 'active_record'

# Change the following to reflect your database settings
  adapter:  'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced'
  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

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

Solution 2 - Ruby on-Rails

It's worth noting that in later versions of activerecord (v3+) you need to require it like so

require "active_record"

Solution 3 - Ruby on-Rails

You can create a minimal script with an in-memory SQLite database in just a few lines. This answer is also available as a Gist.

Inspired by Jon Leighton's blog post on how to post an awesome ActiveRecord bug report.

# Based on 

# Run this script with `$ ruby my_script.rb`
require 'sqlite3'
require 'active_record'

# Use `binding.pry` anywhere in this script for easy debugging
require 'pry'

# Connect to an in-memory sqlite3 database
  adapter: 'sqlite3',
  database: ':memory:'

# Define a minimal database schema
ActiveRecord::Schema.define do
  create_table :shows, force: true do |t|
    t.string :name

  create_table :episodes, force: true do |t|
    t.string :name
    t.belongs_to :show, index: true

# Define the models
class Show < ActiveRecord::Base
  has_many :episodes, inverse_of: :show

class Episode < ActiveRecord::Base
  belongs_to :show, inverse_of: :episodes, required: true

# Create a few records...
show = Show.create!(name: 'Big Bang Theory')

first_episode = show.episodes.create!(name: 'Pilot')
second_episode = show.episodes.create!(name: 'The Big Bran Hypothesis')

episode_names = show.episodes.pluck(:name)

puts "#{} has #{show.episodes.size} episodes named #{episode_names.join(', ')}."
# => Big Bang Theory has 2 episodes named Pilot, The Big Bran Hypothesis.

# Use `binding.pry` here to experiment with this setup.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel CukierView Question on Stackoverflow
Solution 1 - Ruby on-RailsPestoView Answer on Stackoverflow
Solution 2 - Ruby on-RailsAndy HensonView Answer on Stackoverflow
Solution 3 - Ruby on-RailsThomas KlemmView Answer on Stackoverflow