Skip to content

Instantly share code, notes, and snippets.

@nmk
Created February 21, 2013 05:04
Show Gist options
  • Save nmk/5002233 to your computer and use it in GitHub Desktop.
Save nmk/5002233 to your computer and use it in GitHub Desktop.
Eager loading associations of the same class
require "bundler"
Bundler.setup
require "active_record"
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveRecord::Migration.create_table :bugs do |t|
t.string :name
t.integer :reporter_id
t.integer :assignee_id
end
ActiveRecord::Migration.create_table :users do |t|
t.string :name
end
class User < ActiveRecord::Base
end
class Bug < ActiveRecord::Base
belongs_to :reporter, class_name: "User"
belongs_to :assignee, class_name: "User"
end
bob = User.create(name: "Bob")
alice = User.create(name: "Alice")
bug1 = Bug.create(name: "Bug #1", reporter: bob, assignee: alice)
bug2 = Bug.create(name: "Bug #2", reporter: alice, assignee: bob)
ActiveRecord::Base.logger = Logger.new(STDOUT)
Bug.includes([:reporter, :assignee]).load
D, [2013-02-21T06:03:32.769112 #42805] DEBUG -- : Bug Load (0.1ms) SELECT "bugs".* FROM "bugs"
D, [2013-02-21T06:03:32.772696 #42805] DEBUG -- : User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2)
D, [2013-02-21T06:03:32.773746 #42805] DEBUG -- : User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (2, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment