【发布时间】:2015-04-28 20:45:56
【问题描述】:
我正在使用 Rails 4。我正在创建 API 数据库,用户可以在其中从 Facebook Graph API 注册。 如果用户没有头像,则 image_url 为空。
在阅读了 SO 中的答案后,我认为这是为我的响应构建自定义 json 的正确方法。
我创建了 as_json 方法来在创建用户时仅使用应该返回的参数来呈现响应。 这是我创建 json 响应的方法:
def as_json(options={}){
id: self.id,
first_name: self.first_name,
last_name: self.last_name,
auth_token: self.auth_token,
image: {
thumb: "http://domain.com" + self.profile_image.thumb.url
}
}
end
上面的这个方法给我一个错误:no implicit conversion of nil into String。
如果图像存在于我的数据库中,我需要提供绝对图像 url 路径,但如果图像 url 在我的数据库中为空,我不需要提供此参数作为响应。 如何在这个 as_json 方法中编写 if 语句? 这个我试过了,还是不行。
def as_json(options={}){
id: self.id,
first_name: self.first_name,
last_name: self.last_name,
auth_token: self.auth_token,
if !self.profile_image.thumb.url == nil
image: {
thumb: "http://domain.com" + self.profile_image.thumb.url
}
end
}
end
在 Jorge de los Santos 的帮助下,我设法通过以下代码通过 no implicit conversion of nil into String 错误:
def as_json(options={})
response = { id: self.id,
first_name: self.first_name,
last_name: self.last_name,
auth_token: self.auth_token }
if !self.profile_image.thumb.url == nil
image = "http://domain.com" + self.profile_image.thumb.url
response.merge(image: {thumb: image })
end
response
end
但是现在所有的用户都返回了没有图像参数,即使他有一个图像 url。
【问题讨论】:
标签: ruby-on-rails json ruby-on-rails-4