2011-12-09 47 views
0

我有一个Rails 3.1安装与Postgres 8.4。这里是我的宝石版本:Rails 3.1 + postgresql数据库 - SQL语法错误SELECT ... WHERE ... IN

activerecord (3.1.3) 
    activemodel (= 3.1.3) 
    activesupport (= 3.1.3) 
    arel (~> 2.2.1) 
    tzinfo (~> 0.3.29) 
activerecord-jdbc-adapter (1.2.1) 
activerecord-jdbcpostgresql-adapter (1.2.1) 
    activerecord-jdbc-adapter (~> 1.2.1) 
    jdbc-postgres (~> 9.0.0) 

现在,当我做这个查询在我的控制器:

@topics = Topic.find(:all, :conditions => ["\"ForumID\" in ?, @forum_ids]

我得到这个错误:

ActiveRecord::JDBCError: ERROR: syntax error at or near "'abc123'" 
Position: 62: SELECT "topic".* FROM "topic" WHERE ("ForumID" in 'abc123','1234') 
Completed 500 Internal Server Error in 314ms 

ActiveRecord::StatementInvalid (ActiveRecord::JDBCError: ERROR: syntax error at or near "'abc123'" 
Position: 62: SELECT "topic".* FROM "topic" WHERE ("ForumID" in 'abc123','1234')): 

我认为这个问题是圆括号放置在SQL语句中。它应该在之后而不是在“论坛ID”之前。

SELECT "topic".* FROM "topic" WHERE "ForumID" in ('abc123','1234')完美地工作,所以这是在postgresql适配器中的错误,或者我在我的查询中做错了什么?

谢谢。

回答

4

看起来您在查询中缺少圆括号。所以这一块应该工作:

@topics = Topic.find(:all, :conditions => ["ForumID in (?)", @forum_ids]) 

如你on Rails的3.1,这是更好地使用:

@topis = Topic.where("ForumID in (?)", @forum_ids) 
+0

爽!就是这样。谢谢 – Garrett

0

不要你的意思是有

@topics = Topic.find(:all, :conditions => ["\"ForumID\" in ?", @forum_ids] 

通知收盘"在条件。

作为一个侧面说明,你可以用

@topics = Topic.where("\"ForumID\" in ?", @forum_ids) 

,甚至可能为此在Rails 3中(检查语法)

@topics = Topic.where(:ForumID => @forum_ids) 
+0

我确实收到了“。我没有复制和粘贴,所以当我输入问题时我错过了它。 – Garrett