Rails response_with在索引和创建方法上的行为不同

Tho*_*ble 16 ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我在Rails 3.1中构建一个简单的json API.我创建了一个具有两个功能的控制器:

class Api::DogsController < ActionController::Base
  respond_to :json, :xml
  def index
    respond_with({:msg => "success"})
  end

  def create
    respond_with({:msg => "success"})
  end
end
Run Code Online (Sandbox Code Playgroud)

在routes.rb我有

namespace :api do 
  resources :dogs
end
Run Code Online (Sandbox Code Playgroud)

当我向http:// localhost:3000/api/dogs发出get请求时,我从上面得到了正确的json.当我对同一个网址发帖时,我得到了一个rails例外:

ArgumentError in Api::DogsController#create
Nil location provided. Can't build URI.
actionpack (3.1.0) lib/action_dispatch/routing/polymorphic_routes.rb:183:in `build_named_route_call`
actionpack (3.1.0) lib/action_dispatch/routing/polymorphic_routes.rb:120:in `polymorphic_url'
actionpack (3.1.0) lib/action_dispatch/routing/url_for.rb:145:in `url_for'
Run Code Online (Sandbox Code Playgroud)

但是,如果我将创建代码更改为

def create
  respond_with do |format|
    format.json { render :json => {:msg => "success"}}
  end
end
Run Code Online (Sandbox Code Playgroud)

它返回json就好了.

有人能解释一下这里发生了什么吗?

小智 38

在我自己遇到这个问题并克服它之后,我相信我能提供答案.

当你简单地说:

def create
  respond_with({:msg => "success"})
end
Run Code Online (Sandbox Code Playgroud)

rails尝试做的是"猜测"新创建的资源可用的URL,并将其放在HTTP位置标头中.对于一个哈希对象,这个猜测失败了(它推导出的位置是nil,这会导致你看到的错误信息).

要解决此问题,您需要执行以下操作:

def create
  respond_with({:msg => "success"}, :location => SOME_LOCATION)
end
Run Code Online (Sandbox Code Playgroud)

假设您知道新资源的位置.您甚至可以将"nil"指定为"SOME_LOCATION",这将起作用(有点荒谬).