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

Most upvoted comments

@akaspick the correct API is collection.count(:all). You can find this change listed on the CHANGELOG entry of 4.1