是否可以在 def as_json(_opts = {}) 方法上有條件地呈現屬性?
因為,這是我試圖呈現用戶地址屬性的問題,如果不是空白,否則反應會吐出錯誤,所以,如果用戶創建地址,我只想有條件地呈現屬性。
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
uj5u.com熱心網友回復:
條件總是false因為!nil變成true,所以你的條件檢查if self.location.address == true。該address欄位是一個字串或一個nil我相信。這里有幾種構建它的選項。
# 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?
如果將該compact_blank方法應用于散列,則可以完全擺脫條件。
def as_json(_opts = {})
{
id: id,
email: email,
avatar: avatar,
address: location.address
}.compact_blank
end
您可以使用安全導航來確定是否location存在location&.address。
uj5u.com熱心網友回復:
好的,固定!首先你必須檢查關聯模型
def as_json(_opts = {})
response = {
id: id,
email: email,
}
if self.location.present?
address = self.location.address
end
response = response.merge(address: address)
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/342918.html
