2013-05-01 136 views
9

有没有办法在link_to中包含重定向?我想在删除后刷新当前页面。但是,您可以从应用中的多个视图中删除相同的记录。Rails重定向到前一页(后)删除后

这是的link_to:

<%= link_to 'Delete', expense, confirm: 'Are you sure?', method: :delete, :class => 'btn btn-mini btn-danger' %> 

如果没有,是否有意义保存在闪存中current_url [:fromurl]则提出,在控制破坏这样的部分:

respond_to do |format| 
    format.html { redirect_to flash[:fromurl] } 
    format.json { head :no_content } 
    end 

感谢您的帮助!

+2

你有没有考虑远程制作的链接,这样就可以处理与JS特定的股利和这样你就不必重新加载整个页面的刷新? – 2013-05-01 18:00:56

+0

也许'redirect_to:back'? – MrYoshiji 2013-05-01 18:05:10

+0

听起来不错 - 但是,我不知道要开始做。任何你可以指出我解释的地方? – Reddirt 2013-05-01 18:05:24

回答

24

可以使用redirect_to :back

respond_to do |format| 
    format.html { redirect_to :back } 
    format.json { head :no_content } 
end 

它使用头文件 “HTTP_REFERER” 从请求:

redirect_to :back 
# is a shorthand for: 
redirect_to request.env["HTTP_REFERER"] 
+0

MrYoshiji,我想知道你是否愿意为我看这个问题?我真的很感激。 http://stackoverflow.com/questions/16279090/rails-passing-information-from-a-view-to-a-form – Reddirt 2013-05-01 20:12:20

+3

MrYoshiji - redirect_to:back如果从显示页面以外的任何页面中删除。因为,后面试图带你回去显示你刚删除的记录。我发布了一个新问题。 – Reddirt 2013-05-03 16:57:45

+0

@Reddirt你们每个人都知道如何让':back'尝试将你发送到刚删除的记录吗? – Gcap 2016-01-16 00:59:12

2

在Rails 5(Official Docs),您可以使用更新: redirect_back(fallback_location: root_path)

使用此功能将用户重定向到引荐页面(上一页,与redirect_to :back相同)。如果这不可行,则会重定向到控制器中指定的回退位置。

在控制器中的方法的一个例子(在此将用户重定向到该根路径作为备用位置):

def some_method 
    #Your Code Here 
    redirect_back(fallback_location: root_path) 
end 

用于删除expense和重定向回方法的一个例子,用一回退到root_path

def destroy 
    @expense.destroy 
    redirect_back(fallback_location: root_path) 
end 

下面是一些可以用来浏览器重定向到一个特定的页面的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