2017-03-17 64 views
1

我一直在與這個JSON序列化大約一週半的時間。 無論我嘗試使用其他站點解決方案,我都無法獲得完全限定的URL(獨立於服務器的運行位置)。如果我在工作電腦上運行它,並且在生產服務器上運行https://host.name.organization.com/user/X,我的理想解決方案是返回http://localhost:3000/user/X。它必須獨立於我運行服務器的任何系統。而且因爲這個Rails主機位於NGINX反向代理的後面,所以如果它只是從主機頭讀取就會很好。活動模型序列化程序:無法訪問user_url,可以訪問user_path

正如你可以在代碼中看到的,相對路徑(到主機)被定義和完美工作,但從來沒有網址。其他解決方案結束了一個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": "[email protected]", 
    "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" 
    } 
} 

如果這在某種程度上是創業板中的錯誤/丟失功能,我願意把它交給Github repo

回答