Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an anchor to redirect_to :back

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
like image 855
umezo Avatar asked Dec 10 '12 01:12

umezo


2 Answers

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.

like image 159
Ahmad Sherif Avatar answered Oct 21 '22 23:10

Ahmad Sherif


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

like image 31
Kevin Smouts Avatar answered Oct 21 '22 22:10

Kevin Smouts