循环以创建JSON对象

时间:2016-07-08 18:50:09

标签: ruby-on-rails ruby json ruby-on-rails-4 activerecord

只是试图通过我的故事模型循环..并创建JSON对象并将其插入Call并发送它..但我不知道如何循环通过故事..

我已经这样做了:

@stories = Array.new

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

我尝试将循环插入此JSON OBJECT

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

1 个答案:

答案 0 :(得分: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
      }
    }
  }
}