Skip to content

Instantly share code, notes, and snippets.

@ejholmes
Last active January 1, 2016 23:29
Show Gist options
  • Save ejholmes/8216647 to your computer and use it in GitHub Desktop.
Save ejholmes/8216647 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'logger'
# Print out what version we're running
puts "Active Record #{ActiveRecord::VERSION::STRING}"
ActiveRecord::Base.logger = Logger.new(STDOUT)
# Connect to an in-memory sqlite3 database
ActiveRecord::Base.establish_connection( :adapter => 'sqlite3',
:database => ':memory:' )
# Create the minimal database schema necessary to reproduce the bug
ActiveRecord::Schema.define do
create_table "users" do |t|
end
create_table "contacts" do |t|
end
create_table "contact_aliases" do |t|
t.integer :user_id
t.integer :contact_id
end
end
class User < ActiveRecord::Base
has_many :contact_aliases
end
class ContactAlias < ActiveRecord::Base
belongs_to :user
belongs_to :contact
end
class Contact < ActiveRecord::Base
has_many :contact_aliases
has_one :contact_alias
# I want this scope to eager load contact_aliases that are owned by the given
# user.
scope :as_user, -> user {
joins(%(LEFT OUTER JOIN "contact_aliases" on "contact_aliases"."contact_id" = "contacts"."id" AND "contact_aliases"."user_id" = '#{user.id}'))
}
end
user = User.create
contact = Contact.create
contact_alias = ContactAlias.create user: user, contact: contact
contact = Contact.includes.as_user(user).first
# This should be eager loaded but currently triggers another query.
contact.contact_alias
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment