Rails 3: Proper way to Delete resource using respond_with

4.5k views Asked by At

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.

1

There are 1 answers

2
Chirantan On

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