使用rails4 stored_accessor在postgres中搜索jsonb和数组组合

时间:2017-04-20 12:00:23

标签: ruby-on-rails ruby-on-rails-4 activerecord postgresql-9.4 jsonb

我有一个名为Event的模型,其中我有stored_accessor“list”(存储方式如FIREBASE WARNING: Exception was thrown by user callback. Error: Expression has changed after it was checked. Previous value: 'April 10, 2017'. Current value: ''. )。

我需要进行搜索查询o

data: {"list"=>[{"key"=>"key1", "value"=>"value1"}]}

我有一个像

这样的serach params
#<Event id: "1", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key1", "value"=>"value1"}, {"key"=>"key2", "value"=>"value2"}]}, created_at: "2017-04-14 21:06:22", updated_at: "2017-04-20 10:36:08">
#<Event id: "2", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key1", "value"=>"value1"}]}, created_at: "2017-04-14 21:06:22", updated_at: "2017-04-20 10:36:08">
#<Event id: "3", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key11", "value"=>"value11"}, {"key"=>"key12", "value"=>"value12"}]}, created_at: "2017-04-14 21:07:22", updated_at: "2017-04-20 10:37:08">
#<Event id: "4", title: "HHHH", description: nil, data: {"list"=>[{"key"=>"key111", "value"=>"value111"}, {"key"=>"key112", "value"=>"value112"}]}, created_at: "2017-04-14 21:08:22", updated_at: "2017-04-20 10:38:08">

在第一种情况下,它应该返回1) {'key'=> 'key1', 'value'=> 'value1'} 2) ["key"=>"key1", "value"=>"value1"}, {"key"=>"key2", "value"=>"value2"}] id Event1

在第二种情况下,它应该返回2。 (事件如果返回Event id 1都可以接受)。

我不确定json和数组合。 请帮忙。

1 个答案:

答案 0 :(得分:0)

你可以使用PostgreSQL jsonb的运算符@>来完成它。您还需要编写搜索参数的完整路径:{'list' => [{'key'=> 'key1', 'value'=> 'value1'}]}。试试这段代码:

to_contain1 = {'list' => [{'key'=> 'key1', 'value'=> 'value1'}]}
to_contain2 = {'list' => [{'key'=> 'key2', 'value'=> 'value2'}]}

Event.
  where("data @> ?", to_contain1.to_json})
# returns events 1 & 2

Event.
  where("data @> ?", to_contain1.to_json).
  where("data @> ?", to_contain2.to_json)
# returns event 1