怎么逃避? (问号)运算符在Rails中查询Postgresql JSONB类型

我正在使用Rails 4.2和Postgres 9.4来试用新的JSONB数据类型。 我的数据库中的一个JSONB列包含一个数组,我希望能够查询此数组包含特定值的记录。 我想出了如何使用新的JSONB“问号”(“包含”)运算符来完成此操作,如下所示: http : //www.postgresql.org/docs/9.4/static/functions-json.html

所以在原始SQL中我可以像在这个例子中那样工作:

SELECT * FROM people WHERE roles ? '32486d83-4a38-42ba-afdb-f77ca40ea1fc'; 

但我无法通过ActiveRecord看到从Rails中进行此查询的任何方法。 我尝试使用“where”方法进行原始查询,如下所示:

 Person.where("roles ? ?", "32486d83-4a38-42ba-afdb-f77ca40ea1fc") 

但由于问号是用于替换参数的特殊字符,我收到此错误:

ActiveRecord :: PreparedStatementInvalid:在:roles中错误的绑定变量数(1为2)? ?

我想我需要一种方法来逃避“?” 字符,因为我希望它从字面上通过。 我试过了 \? 和?? 没有运气。 任何帮助表示赞赏!

你应该这样称呼如下:

 Person.where("roles ? :name", name: "32486d83-4a38-42ba-afdb-f77ca40ea1fc") 

解决方法。 运行此查询以查找运算符映射到的函数:

 SELECT oprname, oprcode || '(' || format_type(oprleft, NULL::integer) || ', ' || format_type(oprright, NULL::integer) || ')' AS function FROM pg_operator WHERE oprname = '?'; 

它产生了

 oprname function ? jsonb_exists(jsonb, text) ? exist(hstore, text) 

现在在查询中使用函数而不是运算符:

 Person.where("jsonb_exists(roles, ?)", "32486d83-4a38-42ba-afdb-f77ca40ea1fc")