vendredi 7 avril 2017

Customise as_json response in ruby

I am building rest APIs in ruby

I am using @object.as_json() for the response in json format

I am getting stuck in the mid while transfer the data in as_json. I need to more customize the response

I am listing what exactly I want and where I am getting stuck

I am using below code

@videos = Video.all.map{|m| m.as_json(
  only: [:title],
  method: [:watch_count],
  include: {
    user: {
      only: [:first_name],
      method: [:role] 
    }
  } 
).merge(
    is_upvoted: m.is_upvoted(current_user)
) }

But I need to customise it.

1- I need to pass manual key and value (which is not in db) in video and user object, currently it can be possible with video but not with user. It should e possible with parent object and its child associate object. I don't want to to use :method for the same

2-I need to pass parameter in :method, like video model has a method is_upvoted but having a parameter like current user. So I am unable to pass parameter in :method. currently I can do with merge as I am doing but It can not be possible with user object.

3- I need to change key name while use include: {user: {method: []}}. I need to use key "owner" at the place of "user"

Many Thanks in Advance

Aucun commentaire:

Enregistrer un commentaire