From dc7b2f51ed944e7c60a2289ef02290da36222638 Mon Sep 17 00:00:00 2001 From: Chris Salzberg Date: Sun, 1 Dec 2024 11:36:59 +0900 Subject: [PATCH] Fix for Rails 8 issue with select + count This is not ideal but will do as a quick fix. --- lib/mobility/plugins/active_record/query.rb | 27 ++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/mobility/plugins/active_record/query.rb b/lib/mobility/plugins/active_record/query.rb index fe423c34..14e6ca98 100644 --- a/lib/mobility/plugins/active_record/query.rb +++ b/lib/mobility/plugins/active_record/query.rb @@ -21,6 +21,9 @@ module Query requires :query, include: false + ATTRIBUTE_ALIAS_PREFIX = "__mobility_" + ATTRIBUTE_ALIAS = "#{ATTRIBUTE_ALIAS_PREFIX}%s_%s__" + included_hook do |klass, backend_class| plugin = self if options[:query] @@ -39,7 +42,7 @@ module Query class << self def attribute_alias(attribute, locale = Mobility.locale) - "__mobility_%s_%s__" % [attribute, ::Mobility.normalize_locale(locale)] + ATTRIBUTE_ALIAS % [attribute, ::Mobility.normalize_locale(locale)] end def build_query(klass, locale = Mobility.locale, &block) @@ -182,6 +185,28 @@ def order(opts, *rest) end end + if ::ActiveRecord::VERSION::MAJOR >= 8 + # Fix for https://github.com/shioyama/mobility/pull/654#issuecomment-2503479112 + # + # TODO: Make this better + def select_for_count + return super unless klass.respond_to?(:mobility_attribute?) + + if select_values.any? { |value| value.right.start_with?(ATTRIBUTE_ALIAS_PREFIX) } + filtered_select_values = select_values.map do |value| + value.right.start_with?(ATTRIBUTE_ALIAS_PREFIX) ? value.left : value + end + + # Copied from lib/active_record/relation/calculations.rb + with_connection do |conn| + arel_columns(filtered_select_values).map { |column| conn.visitor.compile(column) }.join(", ") + end + else + super + end + end + end + # Return backend node for attribute name. # @param [Symbol,String] name Name of attribute # @param [Symbol] locale Locale