0

I have a jbuilder template which conditionally renders a partial.

json.current_user do
  # ...
  json.avatar_urls do
    json.partial! 'api/users/avatar_urls', avatar: user.avatar if user.avatar
  end
end

When there is an avatar, the resulting JSON looks like (simplified):

"current_user": {
  "avatar_urls": {
    "original": "http://example.com/avatars/example.jpg",
  }
}

But, when there is no avatar, the resulting JSON has no "avatar_urls" object at all:

"current_user": {
}

I want it to always have this object, but I want it to be an empty object:

"current_user": {
  "avatar_urls": {
  }
}

How can I achieve this?

berkes
  • 26,996
  • 27
  • 115
  • 206

1 Answers1

0

Because avatar is returned only when it is not nil, so you can make the assumption that if an avatar is nil, you return default object for the avatar. For example, add somewhere method:

def avatar_for(user)
  return user.avatar if user.avatar.present?
  default_avatar
end

where default_avatar is an object which will be rendered when you invoke

json.partial! 'api/users/avatar_urls', avatar: avatar_for(user)
MC2DX
  • 562
  • 1
  • 7
  • 19