0

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"
  }
  ....
]

1 Answer 1

3

Try the following:

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

And then:

{
  "message" => {
    "attachment" => {
      "type" => "template",
      "payload" => {
        "template_type" => "generic",
        "elements" => @stories
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Right, i tried that like that and it wont make the call.. i think its because the array is with ids and there should be just a title and image : {"id"=>nil, "title"=>"...", "image_url"=>"..."}.. thats what i get but the array is perfect thanks for that a lot!
@LiborZahrádka: there are just title and image_url. Do you need it to be image or image_url?
U are right.. i have to make a call with image but in db im saving it as image_url
Any idea how to exclude id attr from that array? Because even when i dont selected id the id is still there as nil value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.