加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3:为什么我的respond_to语句在从POST请

发布时间:2020-12-17 03:52:32 所属栏目:百科 来源:网络整理
导读: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 met
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请求调用它时,它可以正常工作.你的意见?

更新:
目前,我已将“respond_with(return_hash)”语句替换为“render:json => return_hash.to_json”,它运行正常.不太理想.

解决方法

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

respond_with(*resources,&block) public

这意味着respond_with方法接受资源,而return_hash是哈希,而不是ActiveRecord对象.所以你的代码是错误的.它永远不会奏效.

UPD

为什么这与GET一起使用并且不适用于POST,PUT或DELETE?

我不知道为什么你使用如response_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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读