0

这让我很难调试这个。在我从 SQLite3 迁移到 PostgreSQL 之前,它运行良好。令我感到奇怪的是,还有另一个控制器的代码几乎与此相同,并且该页面运行良好。有人可以帮我吗?

错误:

ActiveRecord::StatementInvalid in Good_posts#index

Showing c:/ruby/mangfeel/app/views/good_posts/index.html.erb where line #3 raised:

PG::Error: ERROR:  syntax error at or near "desc"
LINE 1: ...  "good_posts".* FROM "good_posts"  ORDER BY like desc LIMIT...
                                                         ^
: SELECT  "good_posts".* FROM "good_posts"  ORDER BY like desc LIMIT 15 OFFSET 0

导致问题的good_posts_controller

def index
 @good_posts = GoodPost.paginate(:page => params[:page], order: 'like desc', per_page: 15)
 @good_client_ip = request.remote_ip.encode! 'utf-8'

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @good_posts }
 end
end

post_controller,它具有类似的代码但工作正常:

def index
 @posts = Post.paginate(:page => params[:page], order: 'created_at desc', per_page: 15)
 @client_ip = request.remote_ip.encode! 'utf-8'

 respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @posts }
 end
end

我感谢所有的帮助!

4

1 回答 1

1

LIKE 是一个运算符,因此您不能将其用作列名,除非您将其双引号:

@good_posts = GoodPost.paginate(... order: '"like" desc' ...)

每当 ActiveRecord 在某些 SQL 中生成列名时,它都会为您引用列名;所以.where(:like => 11)将被发送到数据库where "like" = 11,每个人都很高兴。当您在 SQL 片段(例如.where('"like" = ?', 11))中编写列名时,您必须用双引号将其与模式匹配运算符区分开来。如果您将列重命名为不与关键字冲突的内容(例如likes或),您会更开心number_of_likes

于 2012-11-19T07:32:53.417 回答