Posted over 2 years ago. Visible to the public. External content.

ActiveRecord: How to use ActiveRecord standalone within a Ruby script

Re-creating a complex ActiveRecord scenario quickly without setting up a full-blown Rails app can come in handy e.g. when trying to replicate a presumed bug in ActiveRecord with a small script.

# 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 ActiveRecord::Base.establish_connection( adapter: 'sqlite3', database: ':memory:' ) # Define a minimal database schema ActiveRecord::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 end end # Define the models class Show < ActiveRecord::Base has_many :episodes, inverse_of: :show end class Episode < ActiveRecord::Base belongs_to :show, inverse_of: :episodes, required: true end # 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.
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Author of this card:

Thomas Klemm
Last edit:
over 2 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Thomas Klemm to makandropedia