86

How to add a hash parameter in link_to. I need to generate a URL something like this..

/p/generate/#sometext

This is how my code looks now.

link_to "Click",my_path

How to add the hash parameter to my routes method.

Now for the answer

When I posted the question, I didn't got through the url helpers API fully. http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

I did now. :) .I found the answer.

link_to "Click", my_path(:anchor => "sometext")

M.cypher below almost got it. :)

Manjunath Manoharan
  • 4,567
  • 6
  • 28
  • 43

2 Answers2

141

This is how you would usually do it:

link_to 'Click', my_path(anchor: 'sometext')

Your routes don't have much to do with it, since the anchor part (#something) is not transferred to the server, it's a pure client-side thing.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
M. Cypher
  • 6,966
  • 2
  • 34
  • 34
  • I agree that the hash parameter need not be sent to the server..But the :anchor symbol should be inside the routes method – Manjunath Manoharan Aug 13 '11 at 18:38
  • If you also want the trailing slash, `/my_path/#sometext` rather than `/my_path#sometext` you also need to add `trailing_slash: true`, but most people should be fine with the current answer. – 3limin4t0r Aug 23 '21 at 15:28
15

I recognize this is an old post, but I thought I would contribute my recent discovery:

<%= link_to "New Person", polymorphic_path([:new, person], anchor: "profile") %>

See the API Docs for details.

David Vezzani
  • 1,449
  • 16
  • 24