How to add an anchor to redirect_to :back

2019-02-12 22:27发布

I have a blogging application that has posts that can receive votes through a vote action in the posts controller. Because I allow voting in both the index and show views, I redirect_to :back after a vote is made, as below.

def vote
  # voting logic goes here
  redirect_to :back
end

This redirects me to the correct page, but I want to redirect to the specific post within the page. To do this, I added an identifying anchor to my post partial div.

<div id="post_<%= post.id %>">
  <%= post.content %>
</div>

How can I reference this in my redirect_to :back? I tried the below, which doesn't work.

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

Alternatively, if I were to use an if clause for the show and index views, how do I do that? I tried the below, which returns 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

3条回答
够拽才男人
2楼-- · 2019-02-12 22:38

EDIT: ok my bad, got confused. you should look into this:

What's the right way to define an anchor tag in rails?

EDIT2:

the problem you have is that you are calling a helper inside a controller and not inside a view.

I encourage you to look into the view_context method

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

查看更多
男人必须洒脱
3楼-- · 2019-02-12 22:43

Deep in Rails redirecting mechanism, :back simply means redirect to whatever in HTTP_REFERER environment variable (or raise an error if nothing in this variable). So before redirect_to :back in your controller add this line: env["HTTP_REFERER"] += '#some-id', this should do it.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-12 22:48

I ended up using Javascript instead.

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

posts/_post.html.erb

<div class="post_partial" id="post_<%= post.id %>">
  <%= post.content %>
  <div id="vote_button_<%= post.id %>">
    <%= link_to "up", vote_path, method: "post", remote: true %>
  </div>
</div>

posts/vote.js.erb

$('#post_<%= @post.id %>').html('<%= j render @post %>');
查看更多
登录 后发表回答