且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Ruby on Rails中创建锚点并重定向到此特定锚点

更新时间:2022-04-09 18:38:54

看起来你想要使用 link_to 您在问题中的代码。然后在您的评论列表中,您必须确保链接中有一个名为相同内容的锚标记。

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.

所以这个:

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

会产生类似这样的东西

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

 /* html code */     

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

您必须手动处理 #comment _ 否则link_to方法认为您传递的:anchor属性是针对该标记的。

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.