Reputation: 541
I have
def destroy
Event.find(params[:id]).destroy
flash[:info] = "Event deleted"
redirect_to :back
end
And I am able to delete an item from 2 different views. On one view it is a list of items, so I can use :back
and reload the same page. But the other delete is on the view of the item to delete, so once it's gone I want to redirect_to
somewhere different.
My question is how do I tell Rails a different redirect_to
path depending on where the destroy
method is coming from?
Just as a test, I tried using an if statement based on a body class in the html, but the instance variable is not carried into the destroy method (I assume) as it didn't work. e.g.
def destroy
if @body_class == 'one page'
Event.find(params[:id]).destroy
flash[:info] = "Event deleted"
redirect_to :back
elsif @body_class == 'a different page'
Event.find(params[:id]).destroy
flash[:info] = "Event deleted"
redirect_to root_path
end
end
Upvotes: 4
Views: 7753
Reputation: 2333
Pass the params with destroy link. If link is on list, like this:
<%= link_to 'destroy', event_path(event, :from=>"list"), :method=>:delete %>
If on object page:
<%= link_to 'destroy', event_path(event), :method=>:delete %>
And in controller:
def destroy
Event.find(params[:id]).destroy
flash[:info] = "Event deleted"
if params[:from]=='list'
redirect_to :back
else
redirect_to root_url
end
Upvotes: 10