[英]Rails redirect to previous page (back) after delete
Is there a way to include a redirect in a link_to? 有没有办法在link_to中包含重定向? I want to just refresh the current page after a delete.
我想在删除后刷新当前页面。 But, you can delete the same record from multiple views in the app.
但是,您可以从应用程序中的多个视图中删除相同的记录。
This is the link_to: 这是link_to:
<%= link_to 'Delete', expense, confirm: 'Are you sure?', method: :delete, :class => 'btn btn-mini btn-danger' %>
If not, does it make sense to save the current_url in flash[:fromurl] then put that in the Controller destroy section like this: 如果没有,将current_url保存在flash [:fromurl]中然后将其放入Controller destroy部分是这样的:
respond_to do |format|
format.html { redirect_to flash[:fromurl] }
format.json { head :no_content }
end
Thanks for the help! 谢谢您的帮助!
You can use the redirect_to :back
: 你可以使用
redirect_to :back
:
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
It uses the header "HTTP_REFERER" from the request: 它使用来自请求的标题“HTTP_REFERER”:
redirect_to :back
# is a shorthand for:
redirect_to request.env["HTTP_REFERER"]
In Rails 5 ( Official Docs ) you can use the updated: redirect_back(fallback_location: root_path)
在Rails 5( 官方文档 )中,您可以使用更新的:
redirect_back(fallback_location: root_path)
Using this redirects the user to the referring page (previous page, the same as redirect_to :back
). 使用此功能可将用户重定向到引用页面(上一页,与
redirect_to :back
相同)。 If this isn't possible, it then redirects to a fallback location specified in the controller. 如果无法做到这一点,则会重定向到控制器中指定的回退位置。
An example of a method in your controller (this redirects the user to the root path as a fallback location): 控制器中的方法示例(这会将用户重定向到根路径作为后备位置):
def some_method
#Your Code Here
redirect_back(fallback_location: root_path)
end
An example of a method for deleting an expense
and redirecting back, with a fallback to the root_path
: 删除
expense
并重定向的方法示例,其中包含回退到root_path
:
def destroy
@expense.destroy
redirect_back(fallback_location: root_path)
end
Below are some other examples of the fallback_location
's that can be used to redirect the browser back to a specific page, if the referring page cannot be redirected to: 以下是
fallback_location
的一些其他示例,如果无法将引用页面重定向到以下内容,则可以使用该示例将浏览器重定向回特定页面:
redirect_back fallback_location: "http://www.google.com" #Redirects to Google (or any website you specify)
redirect_back fallback_location: "/images/screenshot.jpg" #Redirects to a local image
redirect_back fallback_location: posts_path #Redirects to the 'posts' path
redirect_back fallback_location: new_user_path #Redirects to the new user path
你也可以试试这个。
render :nothing => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.