7

I have a blogging application with comments. Currently, the comments controller has a standard create action

def create    
  @comment = current_user.build(params[:comment])
  respond_to do |format|
  if @comment.save
    format.html { redirect_to @comment.post }
  end
end

After creation, the user is redirected to the blog post for which the comment was made. How do I redirect lower down in the page, to where the new comment is?

posts/show.html.erb

<div id="post_show">
  <%= @post.content %>
  <%= render @post.comments %>
</div>

comments/_comment.html.erb

<div id="comment_partial">
  <%= comment.content %>
</div>

Is there something I can add to my HTML, then reference in my controller? Do I need to "save" the location somehow? Thanks for helping out a newbie!

umezo
  • 1,519
  • 1
  • 19
  • 33
  • 1
    If your comment container has a unique id such as `
    ` then you can append #comment_12345 to the url and this will make sure whatever element with the id `comment_12345` will be scrolled to on the page.
    – Christopher.Cubells Dec 09 '12 at 20:40
  • Hi @Christopher, this is working perfectly for me when redirecting to a named path. However, I'm having trouble using this with redirect_to :back, and put up a new question. Would appreciate any input. http://stackoverflow.com/questions/13793736/how-to-add-an-anchor-to-redirect-to-back – umezo Dec 10 '12 at 02:44

1 Answers1

12

You can use the anchor option in path helpers, e.g.

redirect_to post_path(@comment.post, anchor: 'some-id')
Ahmad Sherif
  • 5,923
  • 3
  • 21
  • 27
  • Thanks @Ahmad. I did exactly that with `
    ` and `post_path(@comment.post, anchor: "comment_#{@comment.id}")`
    – umezo Dec 09 '12 at 21:25
  • HI @Ahmad, this is working perfectly for me when redirecting to a named path. However, I'm having trouble using this with `redirect_to :back`, and put up a new question. Would appreciate any input. http://stackoverflow.com/questions/13793736/how-to-add-an-anchor-to-redirect-to-back – umezo Dec 10 '12 at 02:43
  • thanks, this is the exact answer that i am looking for. – Jigar Bhatt Aug 13 '20 at 16:21