Rails: Find with uppercase column name

Wajeeh Ahsan
Dec 30, 2020

Sometimes, in our DB, we’ve have column with names like maxUser or firstName . In this kind of situations, queries like .having('COUNT(foo.id) > bar.maxUsers' will change maxUsers to maxusers .

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, …

--

--