How to merge another field in object in rails json response How to merge another field in object in rails json response json json

How to merge another field in object in rails json response


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.


Just before render define the object to send (note that if @ad is not a hash, probably it should be converted to hash before):

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

and then:

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


You could use the as_json method, but you need a method that returns the URL directly

class Ad  def video_url    video.url  endend

Then in the render

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

of course if you want you could wrap this into some method,

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

Then the render would look like this

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