4

I have a URL like so http://example.com/?sort=pop

In my view I am using link_to category.name, categories_path(category)

How can I preserve any query string parameters that might already exist on the requesting URL?

So the final link URL would be http://example.com/categories/1?sort=pop

Jason Yost
  • 4,807
  • 7
  • 42
  • 65

3 Answers3

5
<%= link_to category.name, category_path(category, params) %>

Should do the trick

Take care that the default route helper to access a specific Category is category_path. Singular since it's for only one category, makes sense!

Anthony Alberto
  • 10,325
  • 3
  • 34
  • 38
1

Anthony's solution almost worked for me. However, it didn't like just having params as one of the passed through variables. Instead, I had to add params: or :params => to the link. It works just find for me now.

<%= link_to "XLS ", users_path(format: "xls", params: params) %>

kobaltz
  • 6,980
  • 1
  • 35
  • 52
0
<%= link_to category.name, category_path(category,
  request.parameters.merge({:new_params => 42}) ) %>

This should link to the right path, preserve existing parameters and add any new params you might have.

Rails: Preserving GET query string parameters in link_to

Community
  • 1
  • 1
Archonic
  • 5,207
  • 5
  • 39
  • 55