Skip to content
This repository has been archived by the owner on Mar 30, 2022. It is now read-only.

Commit

Permalink
Merge branch 'safe_count_after_select' of github.com:PaySavvy/squeel
Browse files Browse the repository at this point in the history
  • Loading branch information
ernie committed Sep 3, 2013
2 parents 20eb0fa + 518d32c commit 4360bf7
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 34 deletions.
34 changes: 0 additions & 34 deletions lib/squeel/adapters/active_record/4.0/relation_extensions.rb
Expand Up @@ -120,40 +120,6 @@ def dehashified_order_values
end
}
end

# So, building a select for a count query in Active Record is
# pretty heavily dependent on select_values containing strings.
# I'd initially expected that I could just hack together a fix
# to select_for_count and everything would fall in line, but
# unfortunately, pretty much everything from that point on
# in ActiveRecord::Calculations#perform_calculation expects
# the column to be a string, or at worst, a symbol.
#
# In the long term, I would like to refactor the code in
# Rails core, but for now, I'm going to settle for this hack
# that tries really hard to coerce things to a string.
def select_for_count
visited_values = select_visit(select_values.uniq)
if visited_values.any?
string_values = visited_values.map { |value|
case value
when String
value
when Symbol
value.to_s
when Arel::Attributes::Attribute
join_name = value.relation.table_alias || value.relation.name
"#{connection.quote_table_name join_name}.#{connection.quote_column_name value.name}"
else
value.respond_to?(:to_sql) ? value.to_sql : value
end
}
string_values.join(', ')
else
:all
end
end

end
end
end
Expand Down
2 changes: 2 additions & 0 deletions lib/squeel/adapters/active_record/relation_extensions.rb
Expand Up @@ -99,6 +99,8 @@ def select_for_count
end

str_select if str_select && str_select !~ /[,*]/
else
:all
end
end

Expand Down
Expand Up @@ -389,6 +389,10 @@ module ActiveRecord
expect { people.first.name }.to raise_error ActiveModel::MissingAttributeError
end

it 'works with multiple fields in select' do
Article.select("title, body").count.should eq 51
end

it 'allows a function in the select values via Symbol#func' do
relation = Person.select(:max.func(:id).as('max_id'))
relation.first.max_id.should eq 332
Expand Down

0 comments on commit 4360bf7

Please sign in to comment.