2016-02-19 80 views
1

在postgres json字段中,如何使用ActiveRecord查詢匹配item["editions"]包括23的所有數組項目?如何檢查包含嵌套數組中的值

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

回答

0

你有一些額外的逗號和一些缺少逗號:我,要去整理的陣列到以下幾點:

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查詢來完成,你將需要解釋你是如何實際存儲這些數據到數據庫中的,並且包含一些例子。