Rails 3:使用 respond_with 删除资源的正确方法
我正在尝试通过合并respond_with来干燥控制器。当我这样做时,按照 Railscast 中的一些说明,我可以让事情大部分正常工作。问题在于删除资源后的重定向...应该重定向到people_url
...但却尝试加载特定资源。
我找到的示例代码看起来像这样...但是尝试加载刚刚删除的资源失败:
# app/controllers/people_controller.rb
class PeopleController < ApplicationController
respond_to :html, :xml
def destroy
@person = Person.find(params[:id])
flash[:notice] = 'Successfully deleted person.' if @person.destroy
respond_with(@person) # <== spec fails here
end
end
将最后一行更改为 respond_with(@people)
也不起作用(尽管我希望它会......)
经过大量挖掘并尽力理解事情后,我确实让事情正常工作(至少看起来如此。规格通过。应用程序功能):
respond_with(@person, :location => people_url) # <== now it works
那么,这是处理这个问题的正确方法吗? ?似乎凭借 respond_with 背后的所有“魔法”,它会知道删除后它无法重定向到自身?我还认为这个(7个基本的RESTful CRUD方法之一)将是非常基本和初级的,所以大量的例子会比比皆是......但除了那些建议代码不适用于的例子之外,我找不到很多例子我。
希望有人能帮助我理解这里发生的铁路“魔法”,这样当我在路上遇到这种情况时我就不会感到惊讶。
I'm trying to DRY up a controller by incorporating respond_with
. When I do, following some instructions in a Railscast, I get things mostly working. The problem lies in the redirect after deleting a resource...which should be redirecting to people_url
...but instead tries to load the specific resource.
The sample code I found looks like this...But it fails trying to load the resource it just deleted:
# app/controllers/people_controller.rb
class PeopleController < ApplicationController
respond_to :html, :xml
def destroy
@person = Person.find(params[:id])
flash[:notice] = 'Successfully deleted person.' if @person.destroy
respond_with(@person) # <== spec fails here
end
end
changing that last line to respond_with(@people)
doesn't work either (though I had hoped it would...)
After much digging around and trying my best to understand things I did get things to work (at least it would appear so. specs passing. app functional) with this:
respond_with(@person, :location => people_url) # <== now it works
So, is this the correct way to handle this? It seems that with all the 'magic' behind respond_with it would know it can't redirect to itself after a delete? I also figured this (one of 7 basic RESTful CRUD methods) would be pretty basic and rudimentary so plenty of examples would abound...but I haven't been able to find many except the ones suggesting the code that didn't work for me.
Hoping someone can help me understand the rails 'magic' that is occurring here so I won't be surprised when this blows up on me down the road.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正尝试使用已删除的资源进行响应。这就是问题所在。在删除等情况下,仅标头响应有效。将请求标头状态设置为
:ok
就足够了。You are trying to respond with a resource that's deleted. That's what the problem is. In cases such as deletion, header-only responses work. Setting the request header status to
:ok
is enough.