Skip to content

Instantly share code, notes, and snippets.

@Whoops
Created December 7, 2010 03:35
Show Gist options
  • Save Whoops/731414 to your computer and use it in GitHub Desktop.
Save Whoops/731414 to your computer and use it in GitHub Desktop.
create table authors ( id INTEGER primary key, name TEXT not null);
create table posts ( id INTEGER primary key, author_id INTEGER not null, title text not null,
content text not null );
insert into authors (name) values ('some guy');
insert into authors (name) values ('another guy');
--cheat here, I know the first id will be 1
insert into posts(author_id, title, content)
values (1, 'My first article', 'introductory text here');
insert into posts(author_id, title, content)
values (1, 'My second article', 'itermediate text here');
insert into posts(author_id, title, content)
values (1, 'My third article', 'more text here');
insert into posts(author_id, title, content)
values (1, 'My fourth article', 'I am tired of writing articles');
--second author
insert into posts(author_id, title, content)
values (2, 'My first article', 'introductory text here');
insert into posts(author_id, title, content)
values (2, 'My second article', 'itermediate text here');
insert into posts(author_id, title, content)
values (2, 'My third article', 'more text here');
insert into posts(author_id, title, content)
values (2, 'My fourth article', 'I am tired of writing articles');
require 'logger'
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection( :adapter => "sqlite3",
:database => "posts.db")
log = ActiveRecord::Base.logger = Logger.new('log.sql');
class Author < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
belongs_to :author
end
log.debug { "Without includes" }
Author.all.each do |author|
puts author.name
author.posts.each do |post|
puts " #{post.title}"
end
end
log.debug { "With includes" }
Author.includes(:posts).all.each do |author|
puts author.name
author.posts.each do |post|
puts " #{post.title}"
end
end
D, [2010-12-06T20:35:08.950726 #9969] DEBUG -- : Without includes
D, [2010-12-06T20:35:09.001997 #9969] DEBUG -- : Author Load (0.3ms) SELECT "authors".* FROM "authors"
D, [2010-12-06T20:35:09.006422 #9969] DEBUG -- : Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE ("posts".author_id = 1)
D, [2010-12-06T20:35:09.008461 #9969] DEBUG -- : Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE ("posts".author_id = 2)
D, [2010-12-06T20:35:09.008770 #9969] DEBUG -- : With includes
D, [2010-12-06T20:35:09.009076 #9969] DEBUG -- : Author Load (0.1ms) SELECT "authors".* FROM "authors"
D, [2010-12-06T20:35:09.009730 #9969] DEBUG -- : Post Load (0.2ms) SELECT "posts".* FROM "posts" WHERE ("posts".author_id IN (1,2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment