【发布时间】:2017-03-17 15:04:25
【问题描述】:
我已经与这个 JSON 序列化作斗争了大约一个半星期了。 无论我尝试什么 SO / 其他站点解决方案,我都无法获得完全限定的 URL(与服务器运行的位置无关)。我理想的解决方案是如果我在工作电脑上运行它会返回http://localhost:3000/user/X,在生产服务器上运行它会返回https://host.name.organization.com/user/X。它必须独立于我运行服务器的任何系统。而且因为这个 rails 主机位于 NGINX 反向代理之后,所以如果它只是从主机头中读取,那就太好了。
正如您在代码中看到的,相对路径(到主机)已定义并且可以完美运行,但绝不是 url。其他解决方案以 Rails 错误告终,说我需要静态定义(基本上是硬编码)服务器正在运行的 url。
序列化器
class UserSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :email, :firstname, :lastname, :birthdate, :created_at, :updated_at
attribute :uri do
{user_path: user_path(object)}
end
#Latest addition, no visual result, yet no errors either.
link(:self) { user_url(object) }
end
当前 JSON 响应
{
"id": 37,
"email": "test3@test.coma",
"firstname": "Test",
"lastname": "Test",
"birthdate": "2017-03-13",
"created_at": "2017-03-13T00:00:22.982Z",
"updated_at": "2017-03-13T00:00:23.467Z",
"uri": {
"user_path": "/user/37"
}
}
应该是什么(如果在本地运行)
{
Same as above
"uri": {
"user_path":"user/37",
"user_url":"http://localhost:3000/user/37"
}
}
如果这在某种程度上是 gem 中的错误/缺失功能,我愿意将其移交给 Github repo。
【问题讨论】:
标签: ruby-on-rails json active-model-serializers