Ruby Rails 406对块进行响应时出错
当我尝试实现ajax时,出现了一个“406在13ms内不可接受(ActiveRecord:0.6ms)”错误。代码在普通html中工作,没有任何Ruby Rails 406对块进行响应时出错,ruby,ajax,ruby-on-rails-3,Ruby,Ajax,Ruby On Rails 3,当我尝试实现ajax时,出现了一个“406在13ms内不可接受(ActiveRecord:0.6ms)”错误。代码在普通html中工作,没有任何响应块。我已经把问题缩小到了response\u to模块,现在我被难倒了。SO&google上的其他解决方案似乎都不适用或不起作用 在使用respond\u to块时,是什么导致406错误,无论是仅包含html还是包含ajax/js 如何修复406错误 对于format.html,在respond\u to块中使用redirect\u to是否可以,如
响应
块。我已经把问题缩小到了response\u to
模块,现在我被难倒了。SO&google上的其他解决方案似乎都不适用或不起作用
respond\u to
块时,是什么导致406错误,无论是仅包含html还是包含ajax/jsformat.html
,在respond\u to
块中使用redirect\u to
是否可以,如下面的代码所示视图(haml):
class GcalUsersController < ApplicationController
def destroy
@gcal_user = current_user.gcal_user
# if @gcal_user.delete
# flash[:notice] = "#{@gcal_user.username} deleted"
# end
# redirect_to user_root_path # <-- using this in html mode, app works i.e. no 406 error
respond_to do |format|
format.html { redirect_to(user_root_path) } # <-- using this in html mode instead of above line, app fails i.e. 406 error
# format.js # <-- using this in ajax mode, app fails i.e. 406 error
end
end
end
普通html代码
%div.control-group.controls
= button_to "Delete Gcal User", @gcal_user, method: :delete, class: "btn btn-danger"
AJAX代码
%div.control-group.controls
= button_to "Delete Gcal User", @gcal_user, method: :delete, remote: true, class: "btn btn-danger"
用于AJAX的JS代码(coffeescript)
控制器:
class GcalUsersController < ApplicationController
def destroy
@gcal_user = current_user.gcal_user
# if @gcal_user.delete
# flash[:notice] = "#{@gcal_user.username} deleted"
# end
# redirect_to user_root_path # <-- using this in html mode, app works i.e. no 406 error
respond_to do |format|
format.html { redirect_to(user_root_path) } # <-- using this in html mode instead of above line, app fails i.e. 406 error
# format.js # <-- using this in ajax mode, app fails i.e. 406 error
end
end
end
class GcalUsersControllerjquery_ujs
,为method::delete添加功能的gem需要JSON
def destroy
@gcal_user = current_user.gcal_user
@gcal_user.delete
respond_to do |format|
format.html { redirect_to user_root_path }
format.json { head :no_content }
end
end
问题是由路线引起的。使用单数形式的resource:gcal\u user
而不是复数形式的resources:gcal\u users
导致URL的格式不同。单一资源使用“/gcal\u user.[id]”,这导致respond\u to
块认为格式必须是“[id]”,而不是“.js”或“.html”
请参见已尝试,但无效。2件事:没有一个ajax示例提到我需要使用JSON或query_jsgem,所以我认为它应该只与JS一起使用,其次,为什么format.html
(没有JSON或JS)不能在非ajax(即html)版本中使用?method::delete需要jquery_jsgem。您的端点需要一个删除请求,这在标准链接中是不可能的。链接只发送GET请求。您可以使用method=“delete”将按钮包装成一个表单,以获得相同的效果。我明白您的意思。看来jquery_ujs gem已经自动安装在query rails gem中,我确认web页面和application.js文件都有jquery_ujs文件名。请跟我说清楚,因为我想了解发生了什么,你能解释一下为什么在控制器中使用重定向用户_root_path
工作,而使用响应| do | format | format.html{重定向_到用户_root_path}结束
不适用于正常的HTML-NO AJAX按钮代码?使用重定向用户\u root\u路径
立即响应,而无需先检查请求的格式。它可以请求任何格式,并且重定向调用可以工作。这里没有“普通HTML无Ajax”模式。Rails中的DELETE需要在常规按钮上使用JavaScript。您可以将按钮包装在一个
中,以避免使用JS。这是一个很好的开始:否则,尝试搜索“rails删除请求”,看看什么最适合您的情况。