How to use ActiveRecord in a ruby script outside Rails? How to use ActiveRecord in a ruby script outside Rails? ruby ruby

How to use ActiveRecord in a ruby script outside Rails?


require 'active_record'# Change the following to reflect your database settingsActiveRecord::Base.establish_connection(  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 alwaysclass SomeClass < ActiveRecord::Base  #blah, blah, blahend# Now do stuff with itputs SomeClass.find :allsome_class = SomeClass.new


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

require "active_record"


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 http://www.jonathanleighton.com/articles/2011/awesome-active-record-bug-reports/ # Run this script with `$ ruby my_script.rb`require 'sqlite3'require 'active_record'# Use `binding.pry` anywhere in this script for easy debuggingrequire 'pry'# Connect to an in-memory sqlite3 databaseActiveRecord::Base.establish_connection(  adapter: 'sqlite3',  database: ':memory:')# Define a minimal database schemaActiveRecord::Schema.define do  create_table :shows, force: true do |t|    t.string :name  end  create_table :episodes, force: true do |t|    t.string :name    t.belongs_to :show, index: true  endend# Define the modelsclass Show < ActiveRecord::Base  has_many :episodes, inverse_of: :showendclass Episode < ActiveRecord::Base  belongs_to :show, inverse_of: :episodes, required: trueend# 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 "#{show.name} 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.