Elliot
Elliot

Reputation: 13835

Appending text onto current URL through link in rails

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?

Upvotes: 1

Views: 1520

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124419

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"}) %>

Upvotes: 6

Related Questions