Home > database >  Rails def as_json(_opts = {}) conditional attribute
Rails def as_json(_opts = {}) conditional attribute

Time:10-31

Is possible to conditionaly render a attribute on def as_json(_opts = {}) method?

because, here is the issue I'm trying to render user address attr if is not blank otherwise the react spit out an error so, I would like to just conditionally render the attribute if the user creates the address.

  def as_json(_opts = {})
     response = {
      id: id,
      email: email,
      avatar: avatar

    }

    if self.location.address == !nil
      address = self.location.address
      response.merge(address: address)
    end
    response
end

CodePudding user response:

The condition is always false because !nil becomes true, so your condition checks if self.location.address == true. The address field is a string or a nil I believe. Here are several options to construct it.

# Check if an address is not nil but it allows blank a string
if location.address != nil
# The same but more Ruby-ish way
unless location.address.nil?
# Skips empty strings too
unless location.address.blank?
# The same but inversed
if location.address.present?

You can get rid of the condition totally if you apply the compact_blank method to the hash.

def as_json(_opts = {})
  {
    id: id,
    email: email,
    avatar: avatar,
    address: location.address
  }.compact_blank
end

You can use safe navigation to make sure if location is present location&.address.

CodePudding user response:

Ok, fixed! first you must check the association model

  def as_json(_opts = {})

    response = {
      id: id,
 
      email: email,

    }

    if self.location.present?
      address = self.location.address

    end
    response = response.merge(address: address)
  end
  • Related