How to add an anchor to redirect_to :back

ぐ巨炮叔叔 提交于 2019-11-30 19:12:40

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.

Kevin Smouts

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

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 %>');

Under the hood, redirect_back(fallback_location: 'some_path') redirects_to request.referrer and falls back to 'some_path' when things go wrong.

Unfortunately, it does not provide for supplying an anchor. You can work around this by writing a simple private method to simulate it.

def back_with_anchor(anchor: '')
  "#{request.referrer}##{anchor}"
end

You can then do this where needed.

redirect_to back_with_anchor anchor: @record.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!