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

11

我试图通过使用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方法之一)应该很基础和简单,所以应该有很多例子……但是除了建议我不起作用的代码之外,我还没有找到更多的例子。

希望有人可以帮助我理解此处发生的Rails“魔法”,以便在将来出现问题时我不会感到惊讶。

1个回答

5

您试图响应已删除的资源,这就是问题所在。在删除等情况下,仅设置响应头部即可。将请求头状态设置为:ok即可。

head :ok

2
谢谢你,但很遗憾,我仍然感到困惑。你是在建议使用respond_with(head :ok)吗?因为它不起作用。我只熟悉在respond_to块内使用format.xml { head :ok }。所以不确定如何在这种情况下使用respond_with?!? - Meltemi
@Meltemi - 请查看Ryan Bates的ASCIICast:http://asciicasts.com/episodes/224-controllers-in-rails-3 - dennismonsewicz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接