Aditya Nagla Aditya Nagla - 24 days ago 10
Ruby Question

Rails goto another page in particular section

i have

<div id="all-comments">Comments</div>


section on my Posts show page. I have a link on my Posts index page which shows Number of comments and when clicked on comments i want to go to
example.com/posts/1#all-comments
.

Now i am using
<%= link_to post_path(@post) %>
- This generates
example.com/posts/1
but i want #all-comments at the end.

Thanks in advance.

Answer

This is covered (albeit a bit buried) in the docs for link_to:

link_to can also produce links with anchors or query strings:

link_to "Comment wall", profile_path(@profile, anchor: "wall")
# => <a href="/profiles/1#wall">Comment wall</a>

And so:

<%= link_to post_path(@post, anchor: "all-comments") %>
Comments