Rails 4 使用 JBuilder 使用自定义键构建 JSON

Rails 4 building JSON with custom keys using JBuilder

我正在使用 JBuilder 构建 JSON 响应,现在它看起来像:

 json.array!(@work_posts) do |work_post|
 json.extract! work_post, :post_title, :post_body, :salary, :urgently, :contact, :created_at, :updated_at
 json.contact do
   json.emails work_post.contact.emails
   json.phones work_post.contact.phones
   json.links work_post.contact.links
 end
end

响应如下:

[
  {
    "post_title": "Some work",
    "post_body": "work description",
    "salary": "5$/hour",
    "urgently": true,
    "contact": {
         "emails": "",
         "phones": "",
         "links": ""
              },
    "created_at": "2015-10-11T23:46:17.979+05:00",
    "updated_at": "2015-10-11T23:46:17.979+05:00"
    }
]

我想添加自定义键以使响应看起来像:

"result" : "success",   
"data" : [
  {
    "post_title": "Some work",
    "post_body": "work description",
    "salary": "5$/hour",
    "urgently": true,
    "contact": {
         "emails": "",
         "phones": "",
         "links": ""
              },
    "created_at": "2015-10-11T23:46:17.979+05:00",
    "updated_at": "2015-10-11T23:46:17.979+05:00"
    }
]

我应该怎么做才能做到这一点?

我在任何地方都没有看到这样的问题,我终于实现了我想要的。希望它对某人有用。所以答案很明显:我应该使用我真正需要的而不是 json.array! => json.data 然后我只需要把 json.result "success" 放在上面。结果将是:

"result" : "success",   
"data" : [
 {
    "post_title": "Some work",
    "post_body": "work description",
    "salary": "5$/hour",
    "urgently": true,
    "contact": {
         "emails": "",
         "phones": "",
         "links": ""
          },
    "created_at": "2015-10-11T23:46:17.979+05:00",
    "updated_at": "2015-10-11T23:46:17.979+05:00"
  }
]