Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an anchor and redirect to this specific anchor in Ruby on Rails

I'm trying to create unique anchors for every comment on my blog so a person can take the url of an anchor and paste it in their browser, which will automatically load the page and scroll down to the point in the page where their comment starts.

Perhaps I'm going about this the wrong way but I've tried this which was to no avail.

Comment view - Fail 1 - when pasted in a browser this link does not scroll down to the desired position

<%= link_to '#', :controller => 'posts', :action => 'show', :id => comment.post, :anchor => 'comment_' << comment.id.to_s %> 

Comments controller - Fail 2 - Correct url in browser but no scrolling happens it just stays at the top of the page

redirect_to :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_' + @comment.id.to_s 

If someone could help I'd be very grateful :)

UPDATE: The solutions below almost work, however I come out with the following URL which isn't being scrolled to if I click on it.

# i.e. http://localhost:3000/posts/please-work

like image 499
Damian Avatar asked Apr 16 '09 20:04

Damian


People also ask

Can you redirect an anchor link?

The server can only redirect the link at page level. It cannot redirect incoming anchor links, because it never sees the anchor part of the URL.


1 Answers

Actually, anchor is an option for the path, not for the link_to

<%= link_to '#', post_path(comment.post, :anchor => "comment_#{comment.id}") %> 

http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001565

link_to "Comment wall", profile_path(@profile, :anchor => "wall")        # => <a href="/profiles/1#wall">Comment wall</a> 
like image 134
XGamerX Avatar answered Oct 09 '22 10:10

XGamerX