Libor Zahrádka Libor Zahrádka - 4 months ago 8
JSON Question

Rail 4: Loop to create JSON object

just trying to loop thru my Story model.. and create JSON object and insert it into Call and send it.. But i'm not sure how to loop thru Stories..

I've done this:

@stories = Array.new

Story.where(newsletter_id: current_user.selected_newsletter) do |story|
@stories << {
:title => story.title,
:image_url => story.image_url
}
end


and i'm trying ti insert the loop to this JSON OBJECT

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


The array with multiple stories should looks like this:

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

Answer

Try the following:

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

And then:

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