How to use Rails with uppercase column name?

六月ゝ 毕业季﹏ 提交于 2020-05-29 05:00:50

问题


I have the following as part of an AR query:

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

This generates an error:

ActiveRecord::StatementInvalid:
       PG::UndefinedColumn: ERROR:  column bar.maxusers does not exist
                                                                    ^
       HINT:  Perhaps you meant to reference the column "bar.maxUsers".

I am referencing the column bar.maxUsers.

So, apparently AR downcases the query. How to suppress this behavior?

Rails 4.2.10
PostgreSQL

EDIT: SQL:

SELECT ... HAVING COUNT(foo.id) > bar.maxUsers

So it is happening after the to_sql. Maybe from the execute?


回答1:


This isn't an ActiveRecord or AREL issue, this is just how case sensitivity works in SQL and PostgreSQL.

Identifiers in SQL (such as table and column names) are case-insensitive unless they're quoted. Standard SQL says that unquoted identifiers are folded to upper case, PostgreSQL folds them to lower case, hence the bar.maxusers in the error message.

The solution is to quote the offending column name:

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

Note that you must use double quotes for quoting the identifier as single quotes are only for string literals. Also note that identifier quoting is database-specific: standard SQL and PostgreSQL use double quotes, MySQL uses backticks, SQL Server uses brackets, ...



来源:https://stackoverflow.com/questions/51994652/how-to-use-rails-with-uppercase-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!