如何将锚添加到redirect_to:back

我有一个博客应用程序,其post可以通过post控制器中的vote操作接收投票。 因为我允许在索引和显示视图中进行投票,所以我在进行投票后redirect_to :back ,如下所示。

 def vote # voting logic goes here redirect_to :back end 

这会将我重定向到正确的页面,但我想重定向到页面中的特定post。 为此,我在post部分div中添加了一个识别锚点。

 <div id="post_">  

我怎样才能在redirect_to :back引用它redirect_to :back ? 我尝试了以下,这是行不通的。

 # this doesn't work! redirect_to :back, anchor: "post_#{@post.id}" 

或者,如果我对show和index视图使用if子句,我该怎么做? 我尝试了下面的内容,它undefined method 'current_page' for VocabsController返回undefined method 'current_page' for VocabsController

 #this doesn't work! if current_page?(posts_path) redirect_to posts_path(anchor: "post_#{@post.id}" else redirect_to @post end 

深入Rails重定向机制, :back只是意味着重定向到HTTP_REFERER环境变量中的任何内容(如果此变量中没有任何内容,则引发错误)。 所以在redirect_to :back之前redirect_to :back你的控制器中添加这一行: env["HTTP_REFERER"] += '#some-id' ,这应该这样做。

编辑:好吧,我的坏,迷茫。 你应该看看这个:

在rails中定义锚标记的正确方法是什么?

EDIT2:

你遇到的问题是你在控制器内部而不是在视图内部调用帮助器。

我鼓励你研究一下view_context方法

http://jhonynyc.tumblr.com/post/5361328463/use-view-context-inside-rails-3-controller

我最终使用的是Javascript。

posts_controller.rb

 def vote @post = Post.find(params[:id]) #voting logic respond_to do |format| format.html { redirect_to :back } format.js end end 

文章/ _post.html.erb

 
<%= post.content %>
<%= link_to "up", vote_path, method: "post", remote: true %>

文章/ vote.js.erb

 $('#post_<%= @post.id %>').html('<%= j render @post %>');