活动记录占位符/子集条件

时间:2012-08-09 18:11:49

标签: sql ruby-on-rails postgresql activerecord

我有以下查询:

Score.where("build_id => ? AND metric_id => ? ",params[:buildIds], params[:metricIds])

其中params [:buildIds],params [:metricIds]是整数数组。 我收到这个错误:

PG::Error: ERROR:  operator does not exist: integer => integer
LINE 1: SELECT "scores".* FROM "scores"  WHERE (build_id => 1,2 AND ...
                                                         ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT "scores".* FROM "scores"  WHERE (build_id => 1,2 AND metric_id => 1,13 )

任何帮助?

由于

1 个答案:

答案 0 :(得分:2)

最简单的方法是将两个where调用链接在一起,让ActiveRecord找出所需的SQL:

Score.where(:build_id => params[:buildIds]).where(:metric_id => params[:metricIds])

这将在SQL中为您生成IN,因此数据库应该看到如下内容:

where build_id in (1, 2) and metric_id in (1, 13)

错误消息告诉您PostgreSQL中没有=>运算符,两边都有整数。那是因为=>是Ruby语法,而不是PostgreSQL语法(当然,除非你安装了hstore,而hstore的=>需要两边的字符串)。