2016-07-08 252 views
0

只是想循環通過我的故事模式..和創建JSON對象並將其插入到打電話和發..但我不知道如何循環通的故事..循環創建JSON對象

我已經做了這一點:

​​

我試圖TI插入循環這個JSON對象

"message" => { 
    "attachment" => { 
     "type" => "template", 
     "payload" => { 
     "template_type" => "generic", 
     "elements" => [{this is the array}] 
     } 
    } 
} 

與多個故事中的數組應該是這樣的:

[ 
    { 
    "title" => "title....1", 
    "image" => "image....1" 
    }, 
    { 
    "title" => "title....2", 
    "image" => "image....3" 
    } 
    .... 
] 

回答

3

嘗試以下操作:

@stories = Story.where(newsletter_id: current_user.selected_newsletter) 
       .select(:title, 'image_url as image').as_json(except: :id) 

然後:

{ 
    "message" => { 
    "attachment" => { 
     "type" => "template", 
     "payload" => { 
     "template_type" => "generic", 
     "elements" => @stories 
     } 
    } 
    } 
} 
+0

正確的,我試過這樣的,它不會撥打電話..我認爲它,因爲數組是IDS和應該只有一個標題和圖像:'{「id」=> nil,「title」=>「...」,「image_url」=>「...」} .. ..這就是我得到的,但陣列對此非常感謝! – liborza

+0

@LiborZahrádka:只有'title'和'image_url'。你需要它成爲'圖像'或'image_url?' – potashin

+0

ü是正確的..我必須打電話與'圖像',但在數據庫即時將它保存爲'image_url' – liborza