1

Lets say the current page a user is on is:

http://0.0.0.0:3000/posts?direction=asc&sort=title

Its sorted ascending, by title.

Now lets say I have a search engine, that if you searched for "chicken" for example, the url might be:

http://0.0.0.0:3000/posts?direction=asc&search=chicken&sort=title

But instead of searching, I'd like to make a link such as <a href="CODE HERE">Show all results for chicken</a> which appends &search=chicken to url, or if search already has a value, replaces it.

Is this possible?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Elliot
  • 13,580
  • 29
  • 82
  • 118
  • possible duplicate of [link\_to the current page plus/merged with a param](http://stackoverflow.com/questions/5535908/link-to-the-current-page-plus-merged-with-a-param) . This came first, but the other was probably better posed. – Ciro Santilli OurBigBook.com Oct 01 '14 at 07:31
  • possible duplicate of [Add querystring parameters to link\_to](http://stackoverflow.com/questions/2695538/add-querystring-parameters-to-link-to) – Brad Werth Oct 01 '14 at 18:51

1 Answers1

6

You can use the link_to function without a specified controller/action. Just provide the arguments you want and a URL will be created for the current page plus those parameters.

Note that you will need to use the existing params hash and merge in your additional :search item, otherwise your direction and sort arguments will be removed from the URL. Also, if there is an existing params[:search] item, it will be overwritten by the merge.

<%= link_to "Show all results for chicken", params.merge({:search => "chicken"}) %>
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201