2014-11-23 64 views
0

我通過curl創建了一個用戶資源POST,並且我試圖用http Location頭。這是我的routes.rbrails新手:在創建資源時,render:location返回localhost:3000/users.id而不是localhost:3000/users/id

resources: :users, only [:index, :create, :show] 
# get 'users/:id', :to => 'users#view' # removed based on a suggestion 
post 'users', :to => 'users#create', :as => 'user' 

在users_controller(我跳過了異常處理代碼來簡化代碼

def create 
    user = User.create(name: params[:name]) 
    render :json => JSON.pretty_generate(user.as_json), :status => 200, content_type: 'application/json', location: user 
end 

的響應有一個奇怪的HTTP位置頭。用戶10被標識爲用戶。 10,沒有用戶/ 10

HTTP/1.1 201 Created 
Location: http://localhost:3000/users.10 

我如何可以生成一個位置標頭這樣嗎?

HTTP/1.1 201 Created 
Location: http://localhost:3000/users/10 

Thx!

+0

user_path(user)did not work? – Saravanan 2014-11-23 19:23:04

+0

其實,你可以用'show'替換'view'動作並使用默認資源的路由。 – 2014-11-23 20:04:20

+0

Saravanan,user_path()產生了相同的結果(users.10)。 D方,thx爲routes.rb的建議。 – 2014-11-23 21:42:25

回答

1

這裏是解決方案:

def create 
    user = User.create(name: params[:user]) 
    render :json => JSON.pretty_generate(user.as_json), :status => 200, content_type: 'application/json', location: url_for(user) # you did mistake here. 
end 

我希望這將有助於!

+0

我最終在控制器中創建了一個url_for(用戶)。它似乎工作,但似乎不正確,我必須以這種方式硬編碼的網址。 def url_for(user)「users /」+ user.id.to_s end – 2014-11-23 21:52:18

+0

爲什麼你必須做硬編碼? Url_for已被定義。 – Rubyrider 2014-11-23 21:53:52

+0

url_for()返回/users.10而不是/ users/10 – 2014-11-23 22:00:05

相關問題