Skip to content

Instantly share code, notes, and snippets.

@echristopherson
Created October 31, 2011 21:31
Show Gist options
  • Save echristopherson/1329016 to your computer and use it in GitHub Desktop.
Save echristopherson/1329016 to your computer and use it in GitHub Desktop.
require 'active_record'
db_adapter = RUBY_PLATFORM == 'java' ? 'jdbcsqlite3' : 'sqlite3'
#db_name = ':memory:'
db_name = 'sqlite-ar-test.sqlite3'
ActiveRecord::Base.establish_connection adapter: db_adapter, database: db_name
ActiveRecord::Schema.define do
create_table :books, force: true do |t|
t.string :title
t.references :author
end
create_table :authors, force: true do |t|
t.string :name
end
end
class Book < ActiveRecord::Base
# A book has only one author.
belongs_to :author
def author_name
unless author.nil?
author.name
else
''
end
end
def to_s
"Title: #{title}\nAuthor: #{author_name}"
end
end
class Author < ActiveRecord::Base
# An author can have many books.
has_many :books
def to_s
name
end
end
Author.new(name: 'Author 1').save
Author.new(name: 'Author 2').save
Author.new(name: 'Author 3').save
puts "Authors: #{Author.all.inspect}"
Author.all.each do |author|
puts author.to_s
end
Book.new(title: 'Book 1').save
puts "Books: #{Book.all.inspect}"
Book.all.each do |book|
puts book.to_s
end
author2 = Author.find_by_name 'Author 2'
author2.name = 'Ernest Hemingway'
author2.save
p author2
book1 = Book.find_by_title 'Book 1'
book1.author = author2
book1.title = 'A Farewell to arms'
book1.save
p book1
book2 = Book.new(title: 'The Sun also rises')
book2.author = author2
book2.save
author3 = Author.find_by_name 'Author 3'
author3.name = 'Joseph Heller'
author3.save
book3 = Book.new(title: 'Catch-22')
book3.author = author3
book3.save
puts "Books: #{Book.all.inspect}"
Book.all.each do |book|
puts book
puts
end
# TODO
puts 'Hemingway books - a hackish way:'
#Book.find_by_author('Ernest Hemingway').each do |book|
Book.where(author_id: Author.find_by_name('Ernest Hemingway')).each do |book|
puts book
puts
end
# TODO
puts 'Hemingway books - a more elegant way:'
Author.where(name: 'Ernest Hemingway').first.books.each do |book|
puts book
puts
end
puts 'All books - raw SQL:'
#p Book.connection.select_all 'SELECT * FROM books;'
p ActiveRecord::Base.connection.select_all 'SELECT * FROM books;'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment