2

I have a page which simply displays all of the Links in my database sorted by the voteCount. Here is the controller:

class PagesController < ApplicationController
  def index
    params[:per_page] ||= 5
    params[:page]     ||= 1

    @links = Link.order('voteCount DESC').paginate(:page => params[:page], :per_page => params[:per_page])

  end
end

I save query the database using the paginate plugin, and prepend it with:

.order('voteCount DESC')

When I run this command on my local server, it runs fine. However, as soon as I deploy it to heroku, it fails. This is the output I get when I check the logs/execute it in the console:

Link Load (2.0ms)  SELECT "links".* FROM "links" ORDER BY voteCount DESC LIMIT 5 OFFSET 0
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "votecount" does not exist
LINE 1: SELECT  "links".* FROM "links"  ORDER BY voteCount DESC LIMI...
                                                 ^

I've checked using the console, the voteCount column is definitely there. This might be due to the fact that my local environment runs sqlite3 and heroku makes me use postgres ....

Any help would be really appreciated. Thanks.

4

2 回答 2

4

您有区分大小写的问题。当你说这样的话:

create_table :links do |t|
  t.integer :voteCount
end

Rails 会将这样的 SQL 发送到 PostgreSQL 以创建列:

"voteCount" integer

标识符周围的双引号使其区分大小写,这意味着您必须"voteCount"永远引用它。如果你这样说:

.order('"voteCount" DESC')

一切都会奏效。

SQLite 不关心标识符大小写,因此您可以在 SQLite 中说voteCount, votecount, VOTECOUNT, ... ,这并不重要。

Rails 总是引用它在与 PostgreSQL 对话时产生的标识符。通常这无关紧要,Rails 约定是使用小写标识符,而 PostgreSQL 在使用它们之前将不带引号的标识符折叠为小写,因此默认情况下一切正常。

这里有一些相关的最佳实践:

  1. 在同一个堆栈上开发和部署。
  2. 在 PostgreSQL 中使用带有下划线分隔的单词的小写列名。这也恰好与通常的 Ruby 约定相匹配。

我建议您改用vote_count作为列名。

于 2012-09-14T02:09:31.713 回答
1

您的 heroku 应用程序可能尚未迁移该列

heroku run rake db:migrate
于 2012-09-13T23:07:30.250 回答