Why does Rails / ActiveRecord gives a Postgres SyntaxError “non-integer constant in ORDER”?

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

I have some Ruby on Rails / ActiveRecord code that is giving me the following Postgres error:

PG::SyntaxError: ERROR: non-integer constant in ORDER

I'm not sure why since it is a simple fetch ordered by created_at

self.posts.order(created_at: :desc).limit(25) 

What do I do to change this?

回答1:

I am not sure that syntax is supported in older versions of Rails, which is where I suspect you are. Try this instead:

self.posts.order("created_at desc").limit(25) 


回答2:

I have experienced this error as well after switching my Rails app from MySQL to PostgreSQL (my development environment and Gem list are at the bottom of this post).

The error appears to be caused by PostgreSQL expecting the column names in a SQL query to be double-quoted, as I am able to eliminate the error by changing my ".order()" parameter from hash-format to a literal string:

This Rails code triggers the error:

ModelName.where(:attribute => self.id).order(col1: :desc, col2: :asc) 

...and the resulting error:

Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) ModelName Load (1.0ms)  SELECT "model_name".* FROM "model_name" WHERE ("model_name"."attribute" = 14) ORDER BY '{:col1=>:desc, :col2=>:asc}' PG::SyntaxError: ERROR:  non-integer constant in ORDER BY LINE 1: ...E ("model_name"."attribute" = 14) ORDER BY '{:col1=...                                                       ^ 

Whereas this Rails code works without triggering the error message:

ModelName.where(:attribute => self.id).order("\"col1\" desc, \"col2\" asc") 

I know that PostgreSQL is able to correctly interpret non-quoted identifiers, but the format of the query that ActiveRecord generates in this case appears to be ambiguous to Postgresql. Here's a description of PostgreSQL query syntax: http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html

Here's my development environment:

  • Windows 7
  • Ruby 2.1.5p273
  • Rails 3.0.3 (I know it's old...)
  • PostgreSQL 9.4 (on windows)

...and here's the pertinent part of my gem list:

*** LOCAL GEMS ***  abstract (1.0.0) afm (0.2.2) arel (2.0.10) builder (2.1.2) bundler (1.7.7) hashery (2.1.1) i18n (0.6.11) mysql (2.9.1) pg (0.18.1 x86-mingw32) rack (1.2.8) rails (3.0.3) railties (3.0.3) rake (0.9.2.2) ruby-rc4 (0.1.5) sequel (3.31.0) valkyrie (0.0.2) 


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