Skip to content

Commit

Permalink
use statement cache for belongs_to relations
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Apr 22, 2014
1 parent bdd6491 commit 86d6f05
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
Expand Up @@ -416,7 +416,7 @@ def get_records
return scope.to_a if reflection.scope_chain.any?(&:any?)

conn = klass.connection
sc = reflection.association_scope_cache(conn) do
sc = reflection.association_scope_cache(conn, owner) do
StatementCache.create(conn) { |params|
as = AssociationScope.create { params.bind }
target_scope.merge as.scope(self, conn)
Expand Down
Expand Up @@ -39,7 +39,18 @@ def create_scope
end

def get_records
scope.limit(1).to_a
return scope.limit(1).to_a if reflection.scope_chain.any?(&:any?)

conn = klass.connection
sc = reflection.association_scope_cache(conn, owner) do
StatementCache.create(conn) { |params|
as = AssociationScope.create { params.bind }
target_scope.merge(as.scope(self, conn)).limit(1)
}
end

binds = AssociationScope.get_bind_values(owner, reflection.chain)
sc.execute binds, klass, klass.connection
end

def find_target
Expand Down
5 changes: 4 additions & 1 deletion activerecord/lib/active_record/reflection.rb
Expand Up @@ -205,8 +205,11 @@ def initialize(macro, name, scope, options, active_record)
@scope_lock = Mutex.new
end

def association_scope_cache(conn)
def association_scope_cache(conn, owner)
key = conn.prepared_statements
if options[:polymorphic]
key = [key, owner.read_attribute(@foreign_type)]
end
@association_scope_cache[key] ||= @scope_lock.synchronize {
@association_scope_cache[key] ||= yield
}
Expand Down

0 comments on commit 86d6f05

Please sign in to comment.