Rails 3:使用 respond_with 删除资源的正确方法

发布于 2024-10-17 13:33:35 字数 973 浏览 11 评论 0原文

我正在尝试通过合并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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤芳又自赏 2024-10-24 13:33:35

您正尝试使用已删除的资源进行响应。这就是问题所在。在删除等情况下,仅标头响应有效。将请求标头状态设置为 :ok 就足够了。

head :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.

head :ok
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文