ruby-on-railsassociationshas-one

Why as_json does not return empty object in has_one association?


I've user and address. One user has one address. so I use applied following association.

class User < ApplicationRecord
  has_one :address, dependent: :destroy
end

and in controller:

render json: User.find(1).as_json(include: :address)

The problem is:

it returns a JSON object like

{id: 1, name: "abc", address: {id: 1, user_id: 1}}

if I have an address for user id 1.

but I don't have an address of any user. it returns

{id: 1, name: "abc"}

but I want response like

{id: 1, name: "abc", address: {}} 

if user don't have address.


Solution

  • There's probably a more rails-ey way of doing it, but you can just redefine the address attribute:

    class UserSerializer < ActiveModel::Serializer
      ...
      ...
    
      def address
        super || {}
      end
    end
    

    When the serializer checks the address, if it's present it will return the address, and if it's nil or false, it will return an empty hash instead of not appearing.

    EDIT: As per the comment, this needs to go in the UserSerializer and not the User model, edited code above