I'm trying to redirect after a delete depending on where the user came from.
This is the current code in the event controller:
def destroy
@event = Event.find(params[:id])
@event.destroy
respond_to do |format|
format.html { redirect_to events_url }
format.json { head :no_content }
end
end
I changed it to this (thanks MrYoshiji):
format.html { redirect_to :back }
That works if the user was deleting from all pages except the Event show page. Because you then get an error trying to show a record you just deleted.
So, I'm trying to use a params to tell the destroy code where to redirect to.
I'm trying this:
def destroy
@event = Event.find(params[:id])
@event.destroy
@return_url
respond_to do |format|
format.html { redirect_to @return_url }
format.json { head :no_content }
end
end
But, I don't know how to pass the @return_url as a param in the link_to on a show page.
<%= link_to 'Delete', @event, params(@return_url => "some url"), confirm: 'Are you sure?', method: :delete, :class => 'btn btn-danger' %>
How would I pass the url as a param?
Thanks!!
UPDATE1
I changed the Event controller to this:
def destroy
@expense = Expense.find(params[:id])
redirect_url = (request.referer.include?("#{@event.id}/show") ? events_url : :back)
@expense.destroy
respond_to do |format|
format.html { redirect_to redirect_url }
format.json { head :ok }
end
end
This redirects back to the correct page the "Delete Event" button is on - except when I click that button on the show page for the Event.
The redirect wants to show the deleted record.
UDPATE2
OK this worked for my app:
redirect_url = (request.referer.include?("/events/#{@event.id}") ? events_url : :back)
THANKS FOR ALL THE HELP !!
As I commented, you could do the following:
def destroy
@event = Event.find(params[:id])
@event.destroy
redirect_url = (request.referer.include?("#{@event.id}/show") ? events_url : :back)
respond_to do |format|
format.html { redirect_to redirect_url }
format.json { head :no_content }
end
end
(I am not sure you can access to @event.id
right after you deleted it, if not, destroy it after we set the redirect_url
In your view:
<%= link_to 'Delete', event_path(@event, url), confirm: 'Are you sure?', method: :delete, :class => 'btn btn-danger' %>
Here I'm passing the url
variable as a parameter to the controller.
In controller:
...
@return_url = params[:url]
...
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.