Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge another field in object in rails json response

Json response which I send is like that

"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"

I want that video_url also merge with in ad object.

The way I send response now is

render json: {:success=>true, :message=>"Ad detail",:ad=>@ad, :video_url => @ad.video.url}, :status=>200

How I merge it with ad object?

I want to send it like

"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"

 }

My @ad object is

#<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>
like image 418
Haseeb Ahmad Avatar asked Dec 02 '22 13:12

Haseeb Ahmad


1 Answers

First merge {:video_url => @ad.video.url } with @ad then do following:

{:ad =>  @ad.attributes.merge( :video_url => @ad.video.url )}

so your render call would look like following:

render json: {:success=>true, :message=>"Ad detail", ad:  @ad.attributes.merge( :video_url => @ad.video.url )}, :status=>200  

You may need to use @ad.attributes.except("created_at",....) at following code if you don't need some of the attributes of your active record object @ad.

like image 64
sadaf2605 Avatar answered Dec 04 '22 03:12

sadaf2605