如何使用大写列名称的Rails?

B S*_*ven 3 postgresql ruby-on-rails rails-activerecord ruby-on-rails-4.2

我有以下作为AR查询的一部分:

.having('COUNT(foo.id) > bar.maxUsers')

这会产生错误:

ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column bar.maxusers does not exist
                                                                    ^
       HINT:  Perhaps you meant to reference the column "bar.maxUsers".
Run Code Online (Sandbox Code Playgroud)

我正在引用该列bar.maxUsers.

所以,显然AR降低了查询的范围.如何抑制这种行为?

Rails 4.2.10
PostgreSQL

编辑:SQL:

SELECT ... HAVING COUNT(foo.id) > bar.maxUsers
Run Code Online (Sandbox Code Playgroud)

所以它发生在之后to_sql.也许来自execute

mu *_*ort 6

这不是ActiveRecord或AREL问题,这就是SQL和PostgreSQL中区分大小写的原因.

SQL中的标识符(例如表名和列名)不区分大小写,除非它们被引用.标准SQL表示不带引号的标识符被折叠为大写,PostgreSQL将它们折叠成小写,因此bar.maxusers在错误消息中.

解决方案是引用违规列名称:

.having('COUNT(foo.id) > bar."maxUsers"')
Run Code Online (Sandbox Code Playgroud)

请注意,必须使用双引号来引用标识符,因为单引号仅用于字符串文字.另请注意,标识符引用是特定于数据库的:标准SQL和PostgreSQL使用双引号,MySQL使用反引号,SQL Server使用括号,...