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

一曲冷凌霜 提交于 2019-11-27 21:01:42

It looks like you want to use the link_to code that you have in your question. Then in your list of comments you have to make sure that you have an anchor tag named the same thing in the link.

So this:

 <%= link_to 'Your comment', post_path(@comment.post) + "#comment_#{@comment.id.to_s}" %>

will generate something like this

 <a href="localhost:3000/posts/2#1comment_234">Your comment</a>

 /* html code */     

 <a name="comment_1234">This is a comment</a>

You have to manually tack on the #comment_ otherwise the link_to method thinks that the :anchor attribute that you are passing it is for that tag.

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>

Here's an improvement on @XGamerX's answer.

<%= link_to '#', [comment.post, { anchor: dom_id(comment) }] %>

Or

<%= link_to '#', post_path(comment.post, anchor: dom_id(comment)) %>

Try this:

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

this is best way:

<%= link_to '#', post_path(comment.post, anchor: dom_id(comment.id)) %>

These links will scroll down to position where you have code like:

<a name="comment_1"></a>

I don't know if there are helpers that will do it for you, but it is very simple and you can write your own.

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