From 2a97a655eb064c65d6661b91dd2f9dd8c6483745 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 | 22 ++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/mobility/plugins/active_record/query.rb b/lib/mobility/plugins/active_record/query.rb index fe423c34..d67123c2 100644 --- a/lib/mobility/plugins/active_record/query.rb +++ b/lib/mobility/plugins/active_record/query.rb @@ -21,6 +21,8 @@ module Query requires :query, include: false + ATTRIBUTE_ALIAS = "__mobility_%s_%s__" + included_hook do |klass, backend_class| plugin = self if options[:query] @@ -39,7 +41,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 +184,24 @@ def order(opts, *rest) end end + if ::ActiveRecord::VERSION::MAJOR >= 8 + # Fix for https://github.com/shioyama/mobility/pull/654#issuecomment-2503479112 + def select_for_count + return super unless klass.respond_to?(:mobility_attribute?) + + if select_values.any? { |value| value.right.start_with?("__mobility") } + filtered_select_values = select_values.map do |value| + value.right.start_with?("__mobility") ? value.left : value + end + 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