I've been battling with this JSON serialisation for about a week and a half now. Whatever SO / Other site solution I try, I can never get the Fully Qualified URL (indepent of where the server runs). My ideal solution would be the one that would return http://localhost:3000/user/X if I ran it on my work pc, and https://host.name.organization.com/user/X on the production server. It has to be indepent of whatever system I run the server on. And because this rails host is behind a NGINX reverse proxy it would be great if it would just read from the Host Header.
As you can see in the code, the relative path (to the host) is defined and works perfectly, yet never the url. Other solutions ended up with a Rails error saying I need to statically define (basically hardcode) the url the server is running on.
Serializer
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
Current JSON Response
{
"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"
}
}
What it should be (if ran locally)
{
Same as above
"uri": {
"user_path":"user/37",
"user_url":"http://localhost:3000/user/37"
}
}
If this is somehow a bug/missing feature in the gem, i'm willing to take it over to the Github repo .
Add the following line to your ApplicationController:
serialization_scope :view_context
Then in your serializer, you should be able to access it using the following example:
view_context.user_url(object.id)