[英]Rails conditional redirect after delete
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): 我将其更改为此(感谢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中将@return_url作为参数传递。
<%= 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? 如何将url作为参数传递?
Thanks!! 谢谢!!
UPDATE1 更新1
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 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
(我不确定删除后是否可以立即访问@event.id
,否则请在设置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. 在这里,我将url
变量作为参数传递给控制器。
In controller: 在控制器中:
...
@return_url = params[:url]
...
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.