ruby-on-rails – Rails 3:为什么我的respond_to语句在从POST请
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请求调用的 更新: 更新: 解决方法
由于
http://apidock.com/rails/ActionController/MimeResponds/respond_with
这意味着respond_with方法接受资源,而return_hash是哈希,而不是ActiveRecord对象.所以你的代码是错误的.它永远不会奏效. UPD 为什么这与GET一起使用并且不适用于POST,PUT或DELETE? 我不知道为什么你使用如response_with(some_hash)这样奇怪的结构.什么是respond_with方法?
所以传递不是资源而是哈希是很奇怪的. 现在让我们了解它是如何工作的: # 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |