按值数组搜索jsonb列

时间:2017-08-15 12:32:25

标签: sql ruby-on-rails postgresql jsonb

在我的Ruby on Rails项目中,我有SurveyResult模型,其范围如下:

class SurveyResult < ActiveRecord::Base
  scope :with_purpose, -> (purpose) {
    where("raw #>> '{survey, purpose}' = ?", purpose)
  }
end

raw是一个jsonb列。此列中的数据由以下架构表示:

survey: { purpose: 'data' }

如果我尝试获取目的为data的调查结果,则此范围可以正常工作:

SurveyResult.with_purpose('data')

但是当我还想找到一些其他用途的调查结果时:

SurveyResult.with_purpose(['data', 'risk'])

它返回以下错误:

2.3.1 :042 > SurveyResult.with_purpose(['risk', 'data'])
  SurveyResult Load [dev] (1.5ms)  SELECT "survey_results".* FROM "survey_results" WHERE (raw #>> '{survey, purpose}' = 'risk','data')
ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  argument of WHERE must be type boolean, not type record
LINE 1: ...CT "survey_results".* FROM "survey_results" WHERE (raw #>> '...
                                                             ^
: SELECT "survey_results".* FROM "survey_results" WHERE (raw #>> '{survey, purpose}' = 'risk','data')

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

User.where("id = ?", 1)
Corresponding query to the database would look like,
SELECT "users".* FROM "users"  WHERE (id = 1)

User.where("id IN (?)", [1,2,3])
Corresponding query to the database would look like,
SELECT "users".* FROM "users"  WHERE (id IN (1,2,3))

"= ?" this operator expects on a single argument, so if you are passing an array to it an error would be thrown 

ActiveRecord::StatementInvalid: PG::DatatypeMismatch: ERROR:  argument of WHERE must be type boolean, not type record

In order to pass an array you should modify your query to:

"IN (?)", This operator would work if you wanted to pass a single value to it or an array.

Both would work fine
User.where("id IN (?)", 1)
User.where("id IN (?)", [1,2,3])