I’ve recently run into a situation where I needed to apply a group statement to an ActiveRecord scope if a group statement had already been applied. In this case we need to examine the current scope to see if in fact a group statement has already been applied. ActiveRecord::Relation fortunately has a
group_values method that returns an array of all the columns that the query has been grouped by as symbols.
if current_scope.group_values.length > 1 current_scope.group(:another_column) else current_scope end