gpt4 book ai didi

ruby-on-rails - rails 3 : Why might my respond_to statement throw this exception when called from a POST request?

转载 作者:行者123 更新时间:2023-12-04 06:31:14 25 4
gpt4 key购买 nike

respond_to :json, :html
.
.
.
return_hash = {}
return_hash[:result] = "valid"
return_hash[:status] = "#{userName} has successfully registered for tournament #{tourneyID}"
respond_with(return_hash) #<--Throwing expection NoMethodError (undefined method `model_name' for NilClass:Class):

这是堆栈跟踪...
NoMethodError (undefined method `model_name' for NilClass:Class):
app/controllers/tournaments_controller.rb:48:in `register'

Rendered /Users/myname/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.8ms)
Rendered /Users/myname/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (151.8ms)
Rendered /Users/myname/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (211.1ms)

非常感谢!

不确定它是否重要,但我应该添加这是为了响应 POST 请求而调用的

更新:
我有类似的代码可以正常工作,看起来像这样......
 # Store the tourney data
tourney_hash[:tournament_count] = 1
tourney_hash[:tournament_id] = nextTourney.id
tourney_hash[:remaining_time_in_seconds] = remainingTimeInSeconds
respond_with(tourney_hash)

唯一的区别是这段代码是从 GET 请求中调用的,而上面有问题的代码是从 POST 请求中调用的

更新:
当我更改此代码以便从 GET 请求而不是 POST 请求调用它时,它工作正常。你的意见?

更新:
目前,我已经用“render :json => return_hash.to_json”替换了语句“respond_with(return_hash)”,它工作正常。不理想,不过。

最佳答案

由于 http://apidock.com/rails/ActionController/MimeResponds/respond_with

respond_with(*resources, &block) public



这意味着 respond_with方法接受资源同时 return_hash是一个散列,而不是一个 ActiveRecord 对象。所以你的代码是错误的。它永远不会奏效。

UPD

为什么这适用于 GET 而不适用于 POST、PUT 或 DELETE?

我不知道你为什么用这么奇怪的结构 respond_with(some_hash) .什么是 respond_with方法?

respond_with wraps a resource around a responder for default representation



所以不传递资源而是传递散列是很奇怪的。

现在让我们了解它是如何工作的:
# GET request
respond_with(whatever)
# same as
respond_to do |format|
format.html{ } # will render your_action_name.html.erb
end

但!
# POST request
respond_with(whatever)
# is same as
respond_to do |format|
format.html{ redirect_to WHATEVER } # !!!!
end

就是这样respond_with作品

所以你应该传递一个资源给 respond_with但不是别的。所以你的方法是错误的。这就是为什么你有一个错误。因为要 redirect_to return_hash它试图获取它的 model_name生成路径。

就是这样。

UPD 2

要呈现 json,您应该:
respond_to do |format|
format.json{ render :json => return_hash.to_json }
end

关于ruby-on-rails - rails 3 : Why might my respond_to statement throw this exception when called from a POST request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5780856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com