39

A bit of a softball question, but my Google Fu escapes me at the moment.

How do I link to the current page but then specify params to be merged into the query string?

For instance, if the current page is /resources, I want to be able to specify something like current_page_plus(:param => 'attribute') that evaluates out to /resources?param=attribute.

This would hopefully also merge with existing attributes, so if the current page was /resources?a=b&c=d, then current_page_plus(:c => 'e') would evaluate to /resources?a=b&c=e.

Steven
  • 17,796
  • 13
  • 66
  • 118
  • 1
    I've managed to hamfist `link_to "My link", params.merge(:c => 'e')`, but I have a feeling there's a better way to do this. – Steven Apr 04 '11 at 08:02
  • Similar but for internal parameters like `a/:id/b`: http://stackoverflow.com/questions/2543576/rails-link-to-current-page-and-passing-parameters-to-it – Ciro Santilli OurBigBook.com Oct 01 '14 at 08:09

1 Answers1

74

You can use url_for passing the params.

url_for(params.merge(:c => "e"))

If you use an helper like link_to that internally uses url_for you can skip the url_for and pass the has directly.

link_to "Page", params.merge(:c => "e")
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • 1
    If I want to pass in an anchor, which would normally go as an option to the _path or _url method, how would I do that? – Joshua Pinter Sep 30 '13 at 05:32
  • 2
    If you want to pass in an anchor, it would look something like this `link_to "Top", params.merge(c: "e", anchor: "top")` – Ryan Jul 30 '14 at 21:30