Skip to content

Commit

Permalink
Fix for Rails 8 issue with select + count
Browse files Browse the repository at this point in the history
This is not ideal but will do as a quick fix.
  • Loading branch information
shioyama committed Dec 1, 2024
1 parent a0457b9 commit dc7b2f5
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lib/mobility/plugins/active_record/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit dc7b2f5

Please sign in to comment.