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
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
methodhttp://jhonynyc.tumblr.com/post/5361328463/use-view-context-inside-rails-3-controller
Deep in Rails redirecting mechanism,
:back
simply means redirect to whatever inHTTP_REFERER
environment variable (or raise an error if nothing in this variable). So beforeredirect_to :back
in your controller add this line:env["HTTP_REFERER"] += '#some-id'
, this should do it.I ended up using Javascript instead.
posts_controller.rb
posts/_post.html.erb
posts/vote.js.erb