如何检查嵌套数组中是否包含值

时间:2016-02-19 14:12:28

标签: ruby-on-rails json rails-activerecord postgresql-9.1

在postgres json字段中,如何使用ActiveRecord查询匹配item["editions"]包含23的所有数组项?

Topic.create!(                                
  tree: [                                                                         
    {                                                                             
      "title"       => "Title 1",                                                    
      "description" => "Description",                                              
      "editions"    => [23],                                  
    }
   {                                                                             
      "title"       => "Title 2",                                                    
      "description" => "Description",                                              
      "editions"    => [12],                                  
    }                                                                                   
  ]
)          

1 个答案:

答案 0 :(得分:0)

你有一些额外的逗号和一些丢失的逗号:i;我要将数组整理到以下内容:

myarray =  [                                                                         
  {                                                                             
    "title"       => "Title 1",                                                    
    "description" => "Description",                                              
    "editions"    => [23]                     
  },
 {                                                                             
    "title"       => "Title 2",                                                    
    "description" => "Description",                                              
    "editions"    => [12]                                
  }                                                                                   
]
=> [{"title"=>"Title 1", "description"=>"Description", "editions"=>[23]}, {"title"=>"Title 2", "description"=>"Description", "editions"=>[12]}]

matching = myarray.select{|hash| hash["editions"].include?(23)}
=> [{"title"=>"Title 1", "description"=>"Description", "editions"=>[23]}]

这就是你如何使用现有的数据结构,它是数组和哈希的混合。如果您想知道如何通过SQL查询来执行此操作,您需要解释如何将这些数据实际存储在数据库中并包含一些示例。