我通过curl POST创建了一个用户资源,我正在尝试使用http Location标头生成响应。这是我的routes.rb
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 :(得分: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
我希望这会有所帮助!