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

时间:2015-11-25 12:55:49

标签: ruby-on-rails ruby json paperclip rails-api

我发送的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>

4 个答案:

答案 0 :(得分:9)

首先将{: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

答案 1 :(得分:4)

render之前定义要发送的对象(请注意,如果@ad不是哈希值,可能应该先将其转换为哈希值):

#                    ⇓⇓⇓⇓⇓⇓⇓ 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

答案 2 :(得分:2)

您可以使用as_json方法,但需要一个直接返回网址的方法

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

答案 3 :(得分:1)

您可以通过添加以下内容在哈希中添加新密钥和值:

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

我希望这对你有所帮助。