I have a Parent
model which has Children
. If all the Children
of a certain Parent
are deleted, I'd like to automatically delete the Parent
as well.
In a non-AJAX scenario, in the ChildrenController
I would do:
@parent = @child.parent
@child.destroy
if @parent.children.empty?
redirect_to :action => :destroy,
:controller => :parents,
:id => @parent.id
end
But this is impossible when the request is XHR. The redirect causes a GET request.
The only way I can think of to do this with AJAX is add logic to the response RJS, causing it to create a link_to_remote
element, "click" it, and then remove it. It seems ugly. Is there a better way?
Clarification
When I use the term redirect, I do not mean an HTTP redirect. What I mean is that instead of returning the RJS associated with destroying Child
, I want to perform destroy
on Parent
and return the RJS associated with destroying Parent.