rails: Invalid SQL generated when using count with select values
ExampleModel.select(ExampleModel.arel_table[:id]).count
produces this query:
SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#<Arel::Table:0x007f982e9292a8 @name="example_models", @engine=ExampleModel(id: integer, created_at: datetime, updated_at: datetime), @columns=nil, @aliases=[], @table_alias=nil, @primary_key=nil>, name=:id>) FROM "example_models"
ActiveRecord::StatementInvalid: SQLite3::SQLException: unrecognized token: "#": SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#<Arel::Table:0x007f982e9292a8 @name="example_models", @engine=ExampleModel(id: integer, created_at: datetime, updated_at: datetime), @columns=nil, @aliases=[], @table_alias=nil, @primary_key=nil>, name=:id>) FROM "example_models"
This is true of any select
parameters I’ve tried (ExampleModel.arel_table[Arel.star]
, static values, columns, etc.). Rails 3.2 correctly generated a COUNT(*)
in this case regardless of the select
parameters.
A real-world example of this is in a security layer, where you might do something like ExampleModel.select([ExampleModel.arel_table[Arel.star], security_column_1, security_column_2])
for each relation before passing them on to your controllers, who now may perform a count on them. Of course, the controllers should not have to know that there’s a select
in the relation its working with.
Here’s an example you can grab: https://github.com/joshjordan/rails-4-arel-count-fail
I’m happy to work on this issue (especially since its blocking our Rails 4 upgrade 😃, but lack the necessary experience. I’d need some guidance.
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Comments: 20 (11 by maintainers)
Commits related to this issue
- Don't try to count a relation with aliases Work around ActiveRecord count and column aliases issue as described at: <https://github.com/rails/rails/issues/15138#issuecomment-61325080> AR doesn't p... — committed to gitlabhq/gitlabhq by smcgivern 8 years ago
- Fix `#paginate` for complex queries. Rails' `count` method is profoundly brain damaged: * relation.count returns a hash instead of a number if relation contains a GROUP BY clause. That's what `c.r... — committed to evazion/danbooru by evazion 7 years ago
- Fixes MySql2 syntax error by calling 'size' instead of 'count' The bug this is addressing is described here: https://github.com/rails/rails/issues/15138 I chose to use `size` in these cases because... — committed to littlelines/otwarchive by deleted user 7 years ago
- Ao3 5022 rails 4 dot 1 (#2927) * AO3-5022 Bump Rails to 4.1.16 * AO3-5022 Remove with_scope on Work model * AO3-5022 Bump Authlogic version * AO3-5022 Bump to Authlogic 3.4.6 * AO3-5022 R... — committed to otwcode/otwarchive by deleted user 7 years ago
@akaspick the correct API is
collection.count(:all)
. You can find this change listed on the CHANGELOG entry of 4.1