Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Created October 26, 2017 22:48
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaymcgavren/b6568588329d92c1ce5f719363688ad1 to your computer and use it in GitHub Desktop.
Save jaymcgavren/b6568588329d92c1ce5f719363688ad1 to your computer and use it in GitHub Desktop.
Set up Active Record with an in-memory database and model classes, all in a single file.
# Instead of loading all of Rails, load the
# particular Rails dependencies we need
require 'sqlite3'
require 'active_record'
# Set up a database that resides in RAM
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
# Set up database tables and columns
ActiveRecord::Schema.define do
create_table "comments", force: :cascade do |t|
t.text "content"
t.string "name"
t.integer "post_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_comments_on_post_id"
end
create_table "posts", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "body"
end
end
# Set up model classes
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class Comment < ApplicationRecord
belongs_to :post
end
class Post < ApplicationRecord
has_many :comments
end
# Try everything out!
post = Post.new
post.title = "We got a puppy!"
post.body = "Her name is Chai."
post.save
post.comments.create(content: "Awww.")
post.comments.create(content: "So cute!")
Post.find_each do |post|
p post.comments
end
@jaymcgavren
Copy link
Author

Sample output:

$ ruby blog.rb
-- create_table("comments", {:force=>:cascade})
   -> 0.0250s
-- create_table("posts", {:force=>:cascade})
   -> 0.0003s
#<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, content: "Awww.", name: nil, post_id: 1, created_at: "2017-10-26 23:09:04", updated_at: "2017-10-26 23:09:04">, #<Comment id: 2, content: "So cute!", name: nil, post_id: 1, created_at: "2017-10-26 23:09:04", updated_at: "2017-10-26 23:09:04">]>

@LookOnTheBrightSide
Copy link

👍

@raghuvarmabh
Copy link

👍 thanks

@iconcells
Copy link

great demo !

@theotherdon
Copy link

theotherdon commented Sep 6, 2019

Excellent! Thanks for sharing this! Note: You can load your existing schema by calling ActiveRecord::Tasks::DatabaseTasks.migrate after ActiveRecord::Base.establish_connection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment