我发送的Json响应是这样的
"ad": {
"id": 3,
"title": "dgdfg",
"description": "kjlj",
"video_file_name": "SampleVideo_1080x720_1mb.mp4",
"thumbnail_file_name": "images.jpeg",
"campaign_id": null,
"duration": null
},
"video_url": "/system/ads/videos/000/000/003/original/SampleVideo_1080x720_1mb.mp4?1448019186"
我希望 video_url 也与广告对象合并。
我现在发送响应的方式是
render json: {:success=>true, :message=>"Ad detail",:ad=>@ad, :video_url => @ad.video.url}, :status=>200
如何将它与广告对象合并?
我想发个赞
"ad": {
"id": 3,
"title": "dgdfg",
"description": "kjlj",
"video_file_name": "SampleVideo_1080x720_1mb.mp4",
"thumbnail_file_name": "images.jpeg",
"campaign_id": null,
"duration": null,
"video_url": "/system/ads/videos/000/000/003/original/SampleVideo_1080x720_1mb.mp4?1448019186"
}
我的@ad
对象是
#<Ad:0x007efc20495f98
id: 3,
title: "dgdfg",
description: "kjlj",
video_file_name: "SampleVideo_1080x720_1mb.mp4",
video_content_type: "video/mp4",
video_file_size: 1055736,
video_updated_at: Fri, 20 Nov 2015 11:33:06 UTC +00:00,
thumbnail_file_name: "images.jpeg",
thumbnail_content_type: "image/jpeg",
thumbnail_file_size: 9962,
thumbnail_updated_at: Fri, 20 Nov 2015 11:33:22 UTC +00:00,
created_at: Fri, 20 Nov 2015 11:33:22 UTC +00:00,
updated_at: Fri, 20 Nov 2015 11:33:22 UTC +00:00,
campaign_id: nil,
duration: nil>
最佳答案
首先将 {:video_url => @ad.video.url }
与 @ad
合并,然后执行以下操作:
{:ad => @ad.attributes.merge( :video_url => @ad.video.url )}
因此您的渲染调用如下所示:
render json: {:success=>true, :message=>"Ad detail", ad: @ad.attributes.merge( :video_url => @ad.video.url )}, :status=>200
如果您不需要事件记录对象的某些属性,您可能需要在以下代码中使用 @ad.attributes.except("created_at",....)
@广告
。
关于ruby-on-rails - 如何在 rails json 响应中合并对象中的另一个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33917093/