rails newbie:在资源创建时,render:location返回localhost:3000 / users.id而不是localhost:3000 / users / id

时间:2014-11-23 19:11:27

标签: ruby-on-rails ruby ruby-on-rails-3 http-headers

我通过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!

1 个答案:

答案 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

我希望这会有所帮助!