From 382fd76d3d35edfffee9398a40f353f7efe1eb11 Mon Sep 17 00:00:00 2001 From: Ben Aitcheson Date: Tue, 26 May 2026 10:15:26 +1000 Subject: [PATCH] Use lease_connection on Rails 7.2+ in ActiveRecord5Adapter Rails 7.2 soft-deprecated ActiveRecord::Base.connection in favour of lease_connection, which better describes that the caller is acquiring a connection from the pool rather than holding a permanent one (see rails/rails#51230). Prefer lease_connection when available, and fall back to connection on Rails < 7.2 where it is not defined. Refs #893 --- .../model_adapters/active_record_5_adapter.rb | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/cancan/model_adapters/active_record_5_adapter.rb b/lib/cancan/model_adapters/active_record_5_adapter.rb index 68f1142e..048cf624 100644 --- a/lib/cancan/model_adapters/active_record_5_adapter.rb +++ b/lib/cancan/model_adapters/active_record_5_adapter.rb @@ -49,11 +49,22 @@ def sanitize_sql_activerecord5(conditions) def visit_nodes(node) # Rails 5.2 adds a BindParam node that prevents the visitor method from properly compiling the SQL query if self.class.version_greater_or_equal?('5.2.0') - connection = @model_class.send(:connection) + connection = model_connection collector = Arel::Collectors::SubstituteBinds.new(connection, Arel::Collectors::SQLString.new) connection.visitor.accept(node, collector).value else - @model_class.send(:connection).visitor.compile(node) + model_connection.visitor.compile(node) + end + end + + # Rails 7.2 soft-deprecated ActiveRecord::Base.connection in favour of + # lease_connection, which better describes its lifecycle. Fall back to + # connection for Rails < 7.2 where lease_connection is not defined. + def model_connection + if @model_class.respond_to?(:lease_connection) + @model_class.lease_connection + else + @model_class.send(:connection) end end end