如何在 rails json 响应中合并对象中的另一个字段

How to merge another field in object in rails json response

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",....) @ad

就在render之前定义要发送的对象(注意如果@ad不是hash,可能应该先转换成hash):

#                    ⇓⇓⇓⇓⇓⇓⇓ this depends on what @ad currently is
object_to_send = @ad.to_hash.merge(video_url: @ad.video.url)

然后:

render json: { success: true, 
               message: "Ad detail",
               ad: object_to_send }, 
       status: 200

您可以通过添加以下内容在散列中添加新的键和值:

@ad.attributes[:video_url] = @ad.video.url

希望对你有所帮助。

您可以使用 as_json 方法,但您需要一种方法 returns 直接 URL

class Ad
  def video_url
    video.url
  end
end

然后在渲染中

render json: {
  success: true, 
  message: "Ad detail",
  ad: ad.as_json(
    only: {
      :id, :title, :description, :video_file_name, :thumbnail_file_name, :campaign_id, :duration
    },
    methods: :video_url
  ), 
  status: 200

当然,如果您愿意,可以将其包装到某种方法中,

class Ad
  def my_video_json
    as_json(
      only: {
        :id, :title, :description, :video_file_name, :thumbnail_file_name, :campaign_id, :duration
      },
      methods: :video_url
    )
  end
end

那么渲染图会像这样

render json: { success: true, message: "Ad detail", ad: ad.my_video_json }, status: 200